package o2o.web.actions.shop;

import com.alibaba.fastjson.JSON;
import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.agent.ShopAgentRelationMemory;
import o2o.cache.agent.UserAgentRelationMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.shop.*;
import o2o.cache.sys.SysCustomerCache;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.wallet.UserWalletMemory;
import o2o.config.dao.DataDaoSql;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.config.memcached.MemcacheUtil;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.agent.FENCE_RANGE_TYPE;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.order.ORDER_STATUS;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.shop.*;
import o2o.dao.PO.sys.SysCityAdmin;
import o2o.dao.PO.sys.SysCustomerInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.user.browse.BROWSE_HISTORY_TYPE;
import o2o.dao.PO.wallet.UserWallet;
import o2o.dao.VO.agent.CityAgentSchoolVO;
import o2o.dao.VO.agent.CityAgentVO;
import o2o.dao.VO.common.FileUploadInfo;
import o2o.dao.VO.shop.*;
import o2o.service.shop.ShopService;
import o2o.company.model.ShopInfo;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.system.data.SYS_SOS_MODEL_TYPE;
import o2o.task.image.ImageService;
import o2o.task.shop.ShopWorkTaskUtils;
import o2o.utils.CommonUtils;
import o2o.web.actions.agent.CityAgentMan;
import o2o.web.actions.divide.CityAgentFeeMan;
import o2o.web.actions.order.OrderListMan;
import o2o.web.actions.user.User;
import o2o.web.actions.user.UserManagerAction;
import o2o.web.actions.user.browse.UserBrowseHistoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Controller
public class ShopAction {

    @Autowired
    private UserBrowseHistoryService userBrowseHistoryService;

    // 获取商城店铺的店铺信息（喜燕）
    @RequestMapping(method = RequestMethod.POST, value = "integral/default/shop")
    @ResponseBody
    public String get_default_shop(String token) {
        List<ShopInfo> shopInfoList = ShopMemory.getInstance().listOfIntegralShop(SHOP_IS_INTEGRAL.HAS_INTEGRAL_SHOP);
        if (!ValidateUtil.isAbsList(shopInfoList)) {
            return AjaxResult.errorResult("暂时没有该店铺");
        }
        ShopInfo info = shopInfoList.get(0);
        if (info != null) {
            return AjaxResult.successResult(info);
        }
        return AjaxResult.errorResult("未获取到商城店铺信息");
    }

    //获取店铺的基本信息（用户）
    @RequestMapping(method = RequestMethod.POST, value = "/shop/info")
    @ResponseBody
    public String shop_info(String token, String sysAppKey, Long shopId, String shopOwnUsername) {
        if (ValidateUtil.isNotID(shopId) && ValidateUtil.isNull(shopOwnUsername)) {
            return AjaxResult.errorResult("请选择店铺");
        }
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }
        ShopInfo shopInfo = null;
        if (ValidateUtil.isID(shopId)) {
            shopInfo = ShopMemory.getInstance().getShopById(shopId);
        } else {
            shopInfo = ShopMemory.getInstance().getShopByUsername(shopOwnUsername);
        }
        if (null == shopInfo) {
            return AjaxResult.successResult();
        }

        ShopInfoAndGameVO infoVO = ShopService.getInstance().getShopInfoAndGameDetailOne(user, shopInfo);
        if (null != infoVO.getCityAgent()) {
            infoVO.setCityAgentName(infoVO.getCityAgent().getName());
            CityAgentVO cityAgentVO = infoVO.getCityAgent();
            // 计算区间配送费
            CityAgentFeeMan.assignmentCityAgentFeeByTime(cityAgentVO, DateUtils.getCurrTime());
            if (ValidateUtil.isNotAbsDouble(infoVO.getFixedCost()) && ValidateUtil.isNotAbsDouble(infoVO.getWithinDistance()) && ValidateUtil.isNotAbsDouble(infoVO.getOneKmCost())) {
                infoVO.setFixedCost(cityAgentVO.getFixedCost());
                infoVO.setWithinDistance(cityAgentVO.getWithinDistance());
                infoVO.setOneKmCost(cityAgentVO.getOneKmCost());
            }
            // 重量问题 add  by yangtk  2019年5月9日15:36:48
            if (ValidateUtil.isNotAbsDouble(infoVO.getFixedWeightCost()) && ValidateUtil.isNotAbsDouble(infoVO.getWithinWeight()) && ValidateUtil.isNotAbsDouble(infoVO.getOneKgWeightCost())) {
                infoVO.setFixedWeightCost(cityAgentVO.getFixedWeightCost());
                infoVO.setWithinWeight(cityAgentVO.getWithinWeight());
                infoVO.setOneKgWeightCost(cityAgentVO.getOneKgWeightCost());
            }
        }

        if (user != null) {
            userBrowseHistoryService.addOrUpdateBrowseHistory(user.getUsername(), shopId, null, BROWSE_HISTORY_TYPE.BROWSE_HISTORY_TYPE_SHOP);
        }

        return AjaxResult.successResult(infoVO);
    }

    //获取店铺的营业信息
    @RequestMapping(method = RequestMethod.POST, value = "/shop/statistics")
    @ResponseBody
    public String shop_statistics(String token, Long shopId) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("请选择店铺");
        }

        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

//        ShopWallet sellerWallet = ShopWalletMemory.getInstance().getShopWallet(user.getUsername());
        UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());

        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (null == shopInfo) {
            return AjaxResult.errorResult("未获取到该店铺信息");
        }


        ShopStatistics shopStatistics = new ShopStatistics();
        shopStatistics.setIsWork(shopInfo.getIsWork());
        shopStatistics.setIsOpen(shopInfo.getIsOpen());
        shopStatistics.setWorktime(shopInfo.getWorktime());
        if (null == userWallet) {
            shopStatistics.setAccount(0d);
            shopStatistics.setFcAccount(0d);
            shopStatistics.setTodayMoney(0d);
            shopStatistics.setFcTodayMoney(0d);
            shopStatistics.setTodayOrderCount(0l);
        } else {
            shopStatistics.setAccount(userWallet.getMoney());
            shopStatistics.setFcAccount(userWallet.getFcMoney());
            shopStatistics.setTodayMoney(0d);
            shopStatistics.setFcTodayMoney(0d);
            shopStatistics.setTodayOrderCount(0l);
        }

        DateUtils.StartEndOfDayTimestamp se = DateUtils.getStartEndTimestamp(DateUtils.getCurrTime());
        if (null != se) {
            Long startTime = se.startTimestamp;
            Long endTime = se.endTimestamp;
            //当日订单量
            Long count = OrderInfoMemory.getInstance().getShopOneDaysCount(shopId, startTime, endTime);
            shopStatistics.setTodayOrderCount(count);

            //查询当日收入
            StringBuffer sb = new StringBuffer();
            // 查看创业商圈
            if ((shopInfo.getCloudShopType() & CLOUD_SHOP_TYPE.CLOUD_SHOP_TYPE_SQUARE) > 0) {
                sb.append("select sum(a.squareMoney) shopMoney ")
                        .append(" from ").append(PojoTables.OrderPay).append(" a ")
                        .append(" left join ").append(PojoTables.OrderInfo).append(" b on a.orderNo = b.orderNo ")
                        .append(" where a.createTime> ").append(startTime).append(" and a.createTime< ").append(endTime)
                        .append(" and b.squareShopId = ").append(shopId).append(" and a.isOrderCancel = 0 and a.delFlag = 0 AND b.delFlag = 0 ")
                        .append(" and b.orderNo not like 'S%' ")
                        .append(" and ( b.orderStatus = ").append(ORDER_STATUS.OVER).append(" or b.orderStatus = ")
                        .append(ORDER_STATUS.POSTMAN_FINISH).append(" or b.orderStatus = ").append(ORDER_STATUS.SHOP_FINISH).append(")");
            } else {
                sb.append("select sum(a.shopMoney) shopMoney ")
                        .append(" from ").append(PojoTables.OrderPay).append(" a ")
                        .append(" left join ").append(PojoTables.OrderInfo).append(" b on a.orderNo = b.orderNo ")
                        .append(" where a.createTime> ").append(startTime).append(" and a.createTime< ").append(endTime)
                        .append(" and a.sellerId = ").append(shopId).append(" and a.isOrderCancel = 0 and a.delFlag = 0 AND b.delFlag = 0 ")
                        .append(" and ( b.orderStatus = ").append(ORDER_STATUS.OVER).append(" or b.orderStatus = ")
                        .append(ORDER_STATUS.POSTMAN_FINISH).append(" or b.orderStatus = ").append(ORDER_STATUS.SHOP_FINISH).append(")");
            }
            HashMap<String, Object> dbMap = null;
            try {
                dbMap = UserDaoSql.getInstance().queryMapBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
            }

            if (null != dbMap && null != dbMap.get("shopMoney")) {
                Double money = Double.parseDouble(dbMap.get("shopMoney") + "");
                shopStatistics.setTodayMoney(money);
            }
        }

        //每月提现次数
        if (null == SYS_SETTINGS.SHOP_WALLET_POP_MONTH) {
            shopStatistics.setMonthPopTimes(0);
        } else {
            shopStatistics.setMonthPopTimes(SYS_SETTINGS.SHOP_WALLET_POP_MONTH);
        }

        //商户每周提现次数限制
        if (null == SYS_SETTINGS.SHOP_WALLET_POP_WEEK) {
            shopStatistics.setWeekPopTimes(0);
        } else {
            shopStatistics.setWeekPopTimes(SYS_SETTINGS.SHOP_WALLET_POP_WEEK);
        }

        //单词提现限额
        if (null == SYS_SETTINGS.SHOP_WALLET_POP_MONEY) {
            shopStatistics.setPopOneMoney(0);
        } else {
            shopStatistics.setPopOneMoney(SYS_SETTINGS.SHOP_WALLET_POP_MONEY);
        }

        //可预约天数
        if (null == SYS_SETTINGS.APPOINT_AFTER_DATE) {
            shopStatistics.setAppointAfterDate(0);
        } else {
            shopStatistics.setAppointAfterDate(SYS_SETTINGS.APPOINT_AFTER_DATE);
        }

        //可预约到店消费天数
        if (null == SYS_SETTINGS.APPOINTMENT_DATE) {
            shopStatistics.setAppointmentDate(0);
        } else {
            shopStatistics.setAppointmentDate(SYS_SETTINGS.APPOINTMENT_DATE);
        }


        return AjaxResult.successResult(shopStatistics);
    }

    //获取对店铺的评价
    @RequestMapping(method = RequestMethod.POST, value = "/shop/comment/list")
    @ResponseBody
    public String recommend_shop_list(Long shopId, Long createTime, Integer needCount) {
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("请选择店铺");
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);//所有未删除的
        expression.addChild("shopId", shopId);
        if (SYS_SETTINGS.ORDER_COMMENT_NEED_VERIFY == 1) {
            expression.addChild("verifyState", COMMENT_VERIFY_STATE.COMMENT_PASS);
        }
        if (null != createTime && createTime > 0) {
            expression.addChild("createTime", "<", createTime);
        } else if (SYS_SETTINGS.SHOP_COMMENT_SHOW_AFTER_MINUTE != null && SYS_SETTINGS.SHOP_COMMENT_SHOW_AFTER_MINUTE > 0) {
            Long time = DateUtils.getCurrTime() - (SYS_SETTINGS.SHOP_COMMENT_SHOW_AFTER_MINUTE * 60 * 1000L);
            expression.addChild("createTime", "<", time);
        }
        query.addCondition(expression);
        query.addOrders("createTime", "desc");
        query.setPage(1);
        query.setSize(10);

        String sql = DaoUtils.getSql(PojoTables.ShopComment, query);
        List<ShopCommentInfo> list = null;
        try {
            list = (List<ShopCommentInfo>) UserDaoSql.getInstance().list(ShopCommentInfo.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("评论获取失败，请稍后再试");
        }

        Long count = 0L;
        // 查询数量
        if (needCount != null && needCount == 1 && !isNoCount) {
            StringBuffer countSql = new StringBuffer();
            countSql.append(" select count(1) as counts from ")
                    .append(PojoTables.ShopComment)
                    .append(" where delFlag = 0 ").append(" and shopId =").append(shopId);
            if (SYS_SETTINGS.ORDER_COMMENT_NEED_VERIFY == 1) {
                expression.addChild("verifyState", COMMENT_VERIFY_STATE.COMMENT_PASS);
            }
            try {
                count = UserDaoSql.getInstance().getCount(countSql.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (ValidateUtil.isAbsList(list)) {
            List<ShopCommentInfoVO> voList = new ArrayList<ShopCommentInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                ShopCommentInfoVO infoVO = new ShopCommentInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), infoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == infoVO) {
                    continue;
                }
                if (0 == 1 - infoVO.getIsUnknownName()) {
                    infoVO.setCreateUser("");
                    infoVO.setSignPhoto("");
                    infoVO.setName("");
                } else {
                    if (ValidateUtil.isNotNetUrl(infoVO.getSignPhoto())) {
                        infoVO.setSignPhoto(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getSignPhoto());
                    }
                }

                if (ValidateUtil.isNotNetUrl(infoVO.getImage1Url())) {
                    infoVO.setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage1Url());
                }
                if (ValidateUtil.isNotNetUrl(infoVO.getImage2Url())) {
                    infoVO.setImage2Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage2Url());
                }
                if (ValidateUtil.isNotNetUrl(infoVO.getImage3Url())) {
                    infoVO.setImage3Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage3Url());
                }
                if (ValidateUtil.isNotNetUrl(infoVO.getImage4Url())) {
                    infoVO.setImage4Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage4Url());
                }
                // 订单信息
                OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(infoVO.getOrderNo());
                if (info != null) {
                    infoVO.setOrderCreateTime(info.getCreateTime());
                }

                voList.add(infoVO);
            }
            if (needCount != null && needCount == 1) {
                return AjaxResult.successResult(voList, count);
            } else {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }
        if (needCount != null && needCount == 1) {
            return AjaxResult.successResult(null, 0);
        } else {
            return AjaxResult.successResult(0, null);
        }
    }

    //根据店铺id获取代理信息
    @RequestMapping(method = RequestMethod.POST, value = "/shop/agent/info")
    @ResponseBody
    public String shop_agent_info(Long shopId) {
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("请选择店铺");
        }

        Long agentId = ShopAgentRelationMemory.getInstance().getAgentByShopId(shopId);
        if (ValidateUtil.isNotID(agentId)) {
            return AjaxResult.successResult();
        }

        CityAgentSchoolVO cityAgentSchoolVO = CityAgentMan.getCityAgentDetailInfoById(agentId, true, false, false);

        return AjaxResult.successResult(cityAgentSchoolVO);
    }

    //根据店铺id获取店铺服务的商圈列表
    @RequestMapping(method = RequestMethod.POST, value = "/shop/agent/list")
    @ResponseBody
    public String shop_agent_list(Long shopId) {
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("请选择店铺");
        }

        List<Long> agentIdList = ShopAgentRelationMemory.getInstance().agentListOfShopId(shopId);
        if (!ValidateUtil.isAbsList(agentIdList)) {
            return AjaxResult.successResult(0, null);
        }
        List<CityAgentVO> voList = new ArrayList<>();
        for (int i = 0; i < agentIdList.size(); i++) {
            Long id = agentIdList.get(i);
            if (ValidateUtil.isNotID(id)) {
                continue;
            }
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(id);
            if (null == cityAgent) {
                continue;
            }
            CityAgentVO vo = new CityAgentVO();
            try {
                ObjectUtils.copyPropertiesExclude(cityAgent, vo);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            voList.add(vo);
        }

        return AjaxResult.successResult(voList.size(), voList);
    }

    // 获取店铺最后在线时间
    @RequestMapping(method = RequestMethod.POST, value = "/shop/last/online/time")
    @ResponseBody
    public String shop_last_online_time(String token, Long shopId) {
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("店铺id不存在");
        }


        return AjaxResult.successResult();
    }

    /**
     * --------------------------店主-------------------------------
     */
    //修改店铺
    @RequestMapping(method = RequestMethod.POST, value = "/shoper/shop/modify")
    @ResponseBody
    public String shop_modify(String token, ShopInfo info, FileUploadInfo fileUploadInfo, String shopType) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //根据用户获取店铺信息
        List<ShopInfo> shopInfoList = ShopMemory.getInstance().getShopListByUserName(user.getUsername());
        if (null == shopInfoList || shopInfoList.size() <= 0) {
            return AjaxResult.errorResult("您还没有店铺，请联系客服");
        }

        if (shopInfoList.size() != 1) {
            return AjaxResult.errorResult("您有多个店铺，请选择要修改的店铺");
        }

        Long shopId = shopInfoList.get(0).getId();

        if (ValidateUtil.isNull(info.getShopName())) {
            return AjaxResult.errorResult("店铺名称不能为空");
        }
        //获取店铺信息
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (null == shopInfo) {
            return AjaxResult.errorResult("该店铺不存在，请检查后再修改");
        }

        Integer log_lock = shopInfo.getIsLock();
        Integer log_work = shopInfo.getIsWork();

        String imageUrl = "";
        if (fileUploadInfo != null && null != fileUploadInfo.getShopImage()) {
            //存储图片
            String filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getShopImage());
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setImageUrl(filePath);
            imageUrl += ",imageUrl='" + filePath + "'";
        }
        // 店铺背景图
        if (null != fileUploadInfo && (null != fileUploadInfo.getImageB() || ValidateUtil.isNotNull(fileUploadInfo.getBase64ImgB()) || ValidateUtil.isNotNull(fileUploadInfo.getImageUrlB()))) {
            //存储图片
            String filePath = null;
            if (fileUploadInfo.getImageB() != null) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getImageB());
            } else if (ValidateUtil.isNotNull(fileUploadInfo.getBase64ImgB())) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64ImgB());
            } else {
                filePath = fileUploadInfo.getImageUrlB();
            }
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setImageUrlB(filePath);
            imageUrl += ",imageUrlB='" + filePath + "'";
        }
        String deliveryWorkStr = "";
        if (ValidateUtil.isNotNull(info.getDeliveryWorkDays())) {
            deliveryWorkStr = " ,deliveryWorkDays = '" + info.getDeliveryWorkDays() + "' ";
        }
        // 推荐图片
        if (null != fileUploadInfo && (null != fileUploadInfo.getRecomImage() || ValidateUtil.isNotNull(fileUploadInfo.getBase64RecomImg()) || ValidateUtil.isNotNull(fileUploadInfo.getRecomImageUrl()))) {
            //存储图片
            String filePath = null;
            if (fileUploadInfo.getRecomImage() != null) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getRecomImage());
            } else if (ValidateUtil.isNotNull(fileUploadInfo.getBase64RecomImg())) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64RecomImg());
            } else {
                filePath = fileUploadInfo.getRecomImageUrl();
            }
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setRecomImageUrl(filePath);
            imageUrl += ",recomImageUrl='" + filePath + "'";
        }

        info.setOwnUsername(shopInfo.getOwnUsername());

        if (null != info.getLat() && info.getLat() > 0) {
            shopInfo.setLat(info.getLat());
        }
        if (null != info.getLng() && info.getLng() > 0) {
            shopInfo.setLng(info.getLng());
        }

        //食品安全等级
        if (null != info.getFoodSafeLevel()) {
            shopInfo.setFoodSafeLevel(info.getFoodSafeLevel());
        }

        try {
            ObjectUtils.copyPropertiesExclude(info, shopInfo, null);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //打包费
        Double packetPrice = 0d;
        if (null != info.getPacketPrice()) {
            packetPrice = info.getPacketPrice();
        }

        //餐具费
        Integer hasCanJu = 0;//是否提供餐具 0不提供，1提供按订单收费，2按餐具数量收费
        Double canJuPrice = 0d;//餐具费用（1单或1套）
        if (null != info.getHasCanJu() && info.getHasCanJu() > 0) {
            hasCanJu = info.getHasCanJu();
            canJuPrice = info.getCanJuPrice();
        }

        // 预约时间
        String appointAfterTime = "";
        if (ValidateUtil.isNotNull(info.getAppointAfterTime())) {
            appointAfterTime = info.getAppointAfterTime();
        }

        // 自动打印？
        String autoPrint = "";
        if (ValidateUtil.isAbsInteger(info.getAutoPrint()) && (info.getAutoPrint() == 0 || info.getAutoPrint() == 1)) {
            autoPrint = " ,autoPrint=" + info.getAutoPrint() + " ";
        }
        // end
        // 自取优惠比例
        String ziQuAwardRateStr = "";
        if (SYS_SETTINGS.HAS_ZIQU_AWARD == 1 && info.getZiQuAwardRate() != null && info.getZiQuAwardRate() >= 0 && info.getZiQuAwardRate() <= 100) {
            ziQuAwardRateStr += " ,ziQuAwardRate = " + info.getZiQuAwardRate();
        }
        // 团购商品分销
        String shareRateStr = "";
        if (SYS_SETTINGS.HAS_GOODS_DISTRIBUTE == 1 && info.getSharerShareRate() != null && info.getSharerShareRate() >= 0 && info.getSharerShareRate() <= 100) {
            shareRateStr += " ,sharerShareRate = " + info.getSharerShareRate();
        }
        //vr
        String vrUrl = "";
        if (null != shopInfo.getVrUrl()) {
            vrUrl = ",vrUrl = '" + shopInfo.getVrUrl() + "'";
        }

        String geocode = Geohash.encode(shopInfo.getLat(), shopInfo.getLng());
        Long areaPoint = Geohash.getArea(shopInfo.getLat(), shopInfo.getLng());
        shopInfo.setGeocode(geocode);
        shopInfo.setAreaPoint(areaPoint);

        String hasMulCategory = "";
        if (null != info.getHasMulCategory()) {
            hasMulCategory = ",hasMulCategory=" + info.getHasMulCategory();
        }

        //修改
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopInfo).append(" set ")
                .append("shopName='").append(shopInfo.getShopName()).append("',telephone='").append(shopInfo.getTelephone()).append("',address='").append(shopInfo.getAddress())
                .append("',descs='").append(shopInfo.getDescs()).append("',affiche='").append(shopInfo.getAffiche())
                .append("',lng=").append(shopInfo.getLng()).append(",lat=").append(shopInfo.getLat()).append(",geocode='").append(shopInfo.getGeocode())
                .append("',areaPoint=").append(shopInfo.getAreaPoint()).append(",province='").append(shopInfo.getProvince())
                .append("',city='").append(shopInfo.getCity()).append("',county='").append(shopInfo.getCounty()).append("',")
                .append("alipay='").append(shopInfo.getAlipay()).append("',alipayRealName='").append(shopInfo.getAlipayRealName())
                .append("',tenpay='").append(shopInfo.getTenpay()).append("',tenpayopenId='").append(shopInfo.getTenpayopenId())
                .append("',worktime='").append(shopInfo.getWorktime()).append("',startFree=").append(shopInfo.getStartFree())
//                .append(",freeYunFei=").append(freeYunFei).append(",freeYunFeiShop=").append(freeYunFeiShop).append(",freeYunFeiMoney=").append(freeYunFeiMoney)
                .append(",yunfei=").append(shopInfo.getYunfei()).append(autoPrint)
                .append(",appointAfterTime='").append(appointAfterTime).append("',appointmentTime='").append(shopInfo.getAppointmentTime())
//                .append("',isPeiSong=").append(shopInfo.getIsPeiSong()).append(",isDaoDian=").append(shopInfo.getIsDaoDian()).append(",")
                .append("',appointmentDate=").append(shopInfo.getAppointmentDate()).append(",appointAfterDate=").append(shopInfo.getAppointAfterDate())
                .append(",isAppointment=").append(shopInfo.getIsAppointment()).append(",isWork=").append(shopInfo.getIsWork())
                .append(",isBill=").append(shopInfo.getIsBill()).append(",isSeriesSale=").append(shopInfo.getIsSeriesSale())
                .append(",isNewOpen=").append(shopInfo.getIsNewOpen()).append(",autoClose=").append(info.getAutoClose())
                .append(",autoApply=").append(shopInfo.getAutoApply()).append(imageUrl)
                .append(",updateUser='").append(user.getUsername()).append("',ownName='").append(info.getOwnName())
                .append("',foodSafeLevel='").append(shopInfo.getFoodSafeLevel()).append("'")
                .append(",packetPrice=").append(packetPrice).append(",hasCanJu=").append(hasCanJu).append(",canJuPrice=").append(canJuPrice)
                .append(",shopNameLang='").append(info.getShopNameLang()).append("',descsLang='").append(info.getDescsLang())
                .append("',addressLang='").append(info.getAddressLang()).append("',afficheLang='").append(info.getAddressLang())
                .append("', pageVersion = ").append(shopInfo.getPageVersion())
                .append(hasMulCategory)// 商品分类是否有多级  0只有一级，1有多级
                .append(vrUrl)// vr地址
                .append(deliveryWorkStr)
                .append(ziQuAwardRateStr) // 自取优惠比例
                .append(shareRateStr) //
                .append(" ,imgUpVer = 0 ")
                .append(" where id =").append(shopId).append(" and delFlag=0");

        //保存到数据库
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //修改店铺缓存
        ShopMemory.getInstance().modifyById(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        //代理信息联动修改
        modifyAgent(shopInfo, user.getUsername());
        // 增加日志
        ShopWorkTaskUtils.createShopWorkLog(shopInfo.getId(), log_work, shopInfo.getIsWork(), log_lock, shopInfo.getIsLock(), 0, user.getUsername());

        return AjaxResult.successResult();
    }


    // 打开或者关闭 自动打印
    @RequestMapping(method = RequestMethod.POST, value = "/shop/autoPrint/open")
    @ResponseBody
    public String shop_modify(String token, Integer type) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //  操作权限
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        // 操作类型行
        if (type == null || (type != 1 && type != 0)) {
            return AjaxResult.errorResult("请选择操作类型");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (shopInfo == null) {
            return AjaxResult.errorResult("未查询到店铺，请核实");
        }
        // 和当前装态一致
        if (shopInfo.getAutoPrint() != null && shopInfo.getAutoPrint() == type) {
            return AjaxResult.successResult();
        }
        // 更新
        StringBuffer sql = new StringBuffer();
        sql.append("update ").append(PojoTables.ShopInfo)
                .append(" set updateUser='").append(user.getUsername()).append("'")
                .append(",autoPrint = ").append(type)
                .append(" where id =").append(shopInfo.getId());
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败");
        }
        // 缓存
        ShopMemory.getInstance().modifyById(shopInfo.getId());
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopInfo.getId());
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }

    //店铺信息修改-手机端在用
    @RequestMapping(method = RequestMethod.POST, value = "/shop/modify")
    @ResponseBody
    public String shop_shop_modify(String token, ShopInfo info, FileUploadInfo fileUploadInfo, String shopType) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //根据用户获取店铺信息
        List<ShopInfo> shopInfoList = ShopMemory.getInstance().getShopListByUserName(user.getUsername());
        if (null == shopInfoList || shopInfoList.size() <= 0) {
            return AjaxResult.errorResult("您还没有店铺，请联系客服");
        }

        if (shopInfoList.size() != 1) {
            return AjaxResult.errorResult("您有多个店铺，请选择要修改的店铺");
        }

        Long shopId = shopInfoList.get(0).getId();

        if (ValidateUtil.isNull(info.getShopName())) {
            return AjaxResult.errorResult("店铺名称不能为空");
        }
//        if (ValidateUtil.isNull(info.getOwnUsername())) {
//            return AjaxResult.errorResult("店主账号不能为空");
//        }


        //获取店铺信息
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (null == shopInfo) {
            return AjaxResult.errorResult("该店铺不存在，请检查后再修改");
        }
        Integer log_work = shopInfo.getIsWork();
        Integer log_lock = shopInfo.getIsLock();

        String imageUrl = "";
        if (null != fileUploadInfo && (null != fileUploadInfo.getImage() || StringUtils.isNotEmpty(fileUploadInfo.getBase64Img()))) {
            String filePath = StringUtils.isNotEmpty(fileUploadInfo.getBase64Img()) ? JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64Img()) : JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getImage());
            if (null == filePath) {
                return AjaxResult.errorResult("存图片失败");
            }
            info.setImageUrl(filePath);
            imageUrl = ",imageUrl='" + filePath + "'";
        }
        // 店铺背景图
        if (null != fileUploadInfo && (null != fileUploadInfo.getImageB() || ValidateUtil.isNotNull(fileUploadInfo.getBase64ImgB()) || ValidateUtil.isNotNull(fileUploadInfo.getImageUrlB()))) {
            //存储图片
            String filePath = null;
            if (fileUploadInfo.getImageB() != null) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getImageB());
            } else if (ValidateUtil.isNotNull(fileUploadInfo.getBase64ImgB())) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64ImgB());
            } else {
                filePath = fileUploadInfo.getImageUrlB();
            }
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setImageUrlB(filePath);
            imageUrl += ",imageUrlB='" + filePath + "'";
        }
        // 推荐图片
        if (null != fileUploadInfo && (null != fileUploadInfo.getRecomImage() || ValidateUtil.isNotNull(fileUploadInfo.getBase64RecomImg()) || ValidateUtil.isNotNull(fileUploadInfo.getRecomImageUrl()))) {
            //存储图片
            String filePath = null;
            if (fileUploadInfo.getRecomImage() != null) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getRecomImage());
            } else if (ValidateUtil.isNotNull(fileUploadInfo.getBase64RecomImg())) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64RecomImg());
            } else {
                filePath = fileUploadInfo.getRecomImageUrl();
            }
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setRecomImageUrl(filePath);
            imageUrl += ",recomImageUrl='" + filePath + "'";
        }
        String deliveryWorkStr = "";
        if (ValidateUtil.isNotNull(info.getDeliveryWorkDays())) {
            deliveryWorkStr = " ,deliveryWorkDays = '" + info.getDeliveryWorkDays() + "' ";
        }

        info.setOwnUsername(shopInfo.getOwnUsername());
        info.setOwnName(shopInfo.getOwnName());

        if (null != info.getLat() && info.getLat() > 0) {
            shopInfo.setLat(info.getLat());
        }
        if (null != info.getLng() && info.getLng() > 0) {
            shopInfo.setLng(info.getLng());
        }

        try {
            ObjectUtils.copyPropertiesExclude(info, shopInfo, null);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //餐具费
        Integer hasCanJu = 0;//是否提供餐具 0不提供，1提供按订单收费，2按餐具数量收费
        Double canJuPrice = 0d;//餐具费用（1单或1套）
        if (null != info.getHasCanJu() && info.getHasCanJu() > 0) {
            hasCanJu = info.getHasCanJu();
            canJuPrice = info.getCanJuPrice();
        }

        //vr
        String vrUrl = "";
        if (null != shopInfo.getVrUrl()) {
            vrUrl = ",vrUrl = '" + shopInfo.getVrUrl() + "'";
        }
        // 自取优惠比例
        String ziQuAwardRateStr = "";
        if (SYS_SETTINGS.HAS_ZIQU_AWARD == 1 && info.getZiQuAwardRate() != null && info.getZiQuAwardRate() >= 0 && info.getZiQuAwardRate() <= 100) {
            ziQuAwardRateStr += " ,ziQuAwardRate = " + info.getZiQuAwardRate();
        }

        // 团购商品分销
        String shareRateStr = "";
        if (SYS_SETTINGS.HAS_GOODS_DISTRIBUTE == 1 && info.getSharerShareRate() != null && info.getSharerShareRate() >= 0 && info.getSharerShareRate() <= 100) {
            shareRateStr += " ,sharerShareRate = " + info.getSharerShareRate();
        }
        String geocode = Geohash.encode(shopInfo.getLat(), shopInfo.getLng());
        Long areaPoint = Geohash.getArea(shopInfo.getLat(), shopInfo.getLng());
        shopInfo.setGeocode(geocode);
        shopInfo.setAreaPoint(areaPoint);

        String hasMulCategory = "";
        if (null != info.getHasMulCategory()) {
            hasMulCategory = ",hasMulCategory=" + info.getHasMulCategory();
        }

        //修改
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopInfo).append(" set ")
                .append("shopName='").append(shopInfo.getShopName()).append("',telephone='").append(shopInfo.getTelephone()).append("',address='").append(shopInfo.getAddress())
                .append("',descs='").append(shopInfo.getDescs()).append("',affiche='").append(shopInfo.getAffiche())
                .append("',lng=").append(shopInfo.getLng()).append(",lat=").append(shopInfo.getLat()).append(",geocode='").append(shopInfo.getGeocode())
                .append("',areaPoint=").append(shopInfo.getAreaPoint()).append(",province='").append(shopInfo.getProvince())
                .append("',city='").append(shopInfo.getCity()).append("',county='").append(shopInfo.getCounty()).append("',")
                .append("alipay='").append(shopInfo.getAlipay()).append("',alipayRealName='").append(shopInfo.getAlipayRealName())
                .append("',tenpay='").append(shopInfo.getTenpay()).append("',tenpayopenId='").append(shopInfo.getTenpayopenId())
                .append("',worktime='").append(shopInfo.getWorktime()).append("',startFree=").append(shopInfo.getStartFree())
//                .append(",freeYunFei=").append(freeYunFei).append(",freeYunFeiShop=").append(freeYunFeiShop).append(",freeYunFeiMoney=").append(freeYunFeiMoney)
                .append(",appointmentTime='").append(shopInfo.getAppointmentTime())
                .append("',yunfei='").append(shopInfo.getYunfei())
//                .append("',isPeiSong=").append(shopInfo.getIsPeiSong()).append(",isDaoDian=").append(shopInfo.getIsDaoDian()).append(",")
                .append("',appointmentDate=").append(shopInfo.getAppointmentDate()).append(",appointAfterDate=").append(shopInfo.getAppointAfterDate())
                .append(",isAppointment=").append(shopInfo.getIsAppointment()).append(",isWork=").append(shopInfo.getIsWork())
                .append(",isBill=").append(shopInfo.getIsBill()).append(",isSeriesSale=").append(shopInfo.getIsSeriesSale())
                .append(",isNewOpen=").append(shopInfo.getIsNewOpen()).append(",autoClose=").append(shopInfo.getAutoClose())
                .append(",autoApply=").append(shopInfo.getAutoApply()).append(imageUrl)
                .append(",updateUser='").append(user.getUsername()).append("'")
                .append(",hasCanJu=").append(hasCanJu).append(",canJuPrice=").append(canJuPrice)
                .append(hasMulCategory)
                .append(vrUrl)
                .append(deliveryWorkStr)
                .append(ziQuAwardRateStr)
                .append(shareRateStr)
                .append(" ,imgUpVer = 0 ")
                .append(" where id =").append(shopId).append(" and delFlag=0");


        //保存到数据库
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试.");
        }

        //修改店铺缓存
        ShopMemory.getInstance().modifyById(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        // 增加日志
        ShopWorkTaskUtils.createShopWorkLog(shopInfo.getId(), log_work, shopInfo.getIsWork(), log_lock, shopInfo.getIsLock(), 0, user.getUsername());
        return AjaxResult.successResult();
    }


    //营业状态修改
    @RequestMapping(method = RequestMethod.POST, value = "/shop/status/modify")
    @ResponseBody
    public String shop_status_modify(String token, Long shopId, Integer isWork, Integer isOpen, Integer isStopWork) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("该选择要修改的店铺");
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您不是店主无权修改");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (null == shopInfo) {
            return AjaxResult.errorResult("店铺不存在");
        }
        Integer log_work = shopInfo.getIsWork();
        Integer log_lock = shopInfo.getIsLock();
        if (0 == 1 - isWork && 0 == shopInfo.getIsLock()) {
            return AjaxResult.errorResult("您的店铺已被锁定，无法上班");
        }
        if (null == isWork) {
            isWork = 0;
        }
        String isAutoClose = "";
        if (isWork == 1) { // 上班的话
            if (SYS_SETTINGS.SHOP_AUTO_CLOSE_MODE == 2) { // 2.0 上班同时会自动上下班
                isAutoClose = ",autoClose = " + 0;
            }
        } else {
            // 下班的话
            if (isStopWork != null && isStopWork == 1) {
                isAutoClose = ",autoClose = " + 1;
            }
        }

        if (null == isOpen) {
            isOpen = shopInfo.getIsOpen();
        }
        Long nowTime = DateUtils.getCurrTime();
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopInfo).append(" set updateUser='").append(user.getUsername()).append("',isWork=").append(isWork).append(",isOpen=").append(isOpen)
                .append(",manualWorkTime=").append(nowTime)
                .append(isAutoClose)
                .append(" where delFlag = 0 and id =").append(shopId);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //缓存更新
        ShopMemory.getInstance().modifyById(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        ShopWorkTaskUtils.createShopWorkLog(shopInfo.getId(), log_work, isWork, log_lock, shopInfo.getIsLock(), 0, user.getUsername());
        return AjaxResult.successResult();
    }

    //营业设置
    @RequestMapping(method = RequestMethod.POST, value = "/shop/settings")
    @ResponseBody
    public String shop_status_settings(String token, Long shopId, Integer isWork, String worktime,
                                       Double startFree, Double yunfei, Double packetPrice,
                                       Integer isDaoDian,
                                       Integer isPeiSong,
                                       Integer ziQuAwardRate,
                                       Integer sharerShareRate,
//                                       Double freeYunFei, Double freeYunFeiShop, Double freeYunFeiMoney,
                                       Integer isAppointment,
                                       Integer isBill, Integer isSeriesSale, Integer autoClose, Integer autoApply, String workDate, String applyTime,
                                       Integer appointmentDate, String appointmentTime, Integer appointAfterDate, String appointAfterTime,
                                       Integer hasMulCategory,
                                       String autoApplyTime, String affiche) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("该选择要修改的店铺");
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您不是店主无权修改");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);

        if (null == shopInfo) {
            return AjaxResult.errorResult("店铺不存在，请重试");
        }
        Integer log_work = shopInfo.getIsWork();
        Integer log_lock = shopInfo.getIsLock();
        // 自取优惠比例
        String ziQuAwardRateStr = "";
        if (SYS_SETTINGS.HAS_ZIQU_AWARD == 1 && ziQuAwardRate != null && ziQuAwardRate >= 0 && ziQuAwardRate <= 100) {
            ziQuAwardRateStr += " ,ziQuAwardRate = " + ziQuAwardRate;
        }
        // 分成比例
        String shareRateStr = "";
        if (SYS_SETTINGS.HAS_GOODS_DISTRIBUTE == 1 && sharerShareRate != null && sharerShareRate >= 0 && sharerShareRate <= 100) {
            shareRateStr += " ,sharerShareRate = " + sharerShareRate;
        }
        String manualWorkTime = "";
        //是否营业
        if (null == isWork) {
            isWork = shopInfo.getIsWork();
        } else {
            Long nowTime = DateUtils.getCurrTime();
            manualWorkTime = ",manualWorkTime=" + nowTime;
        }
        //营业时间
//        if (ValidateUtil.isNull(worktime)) {
//            worktime = shopInfo.getWorktime();
//        }
        if (worktime == null) {
            worktime = shopInfo.getWorktime();
        }
        if (0 == 1 - isWork && 0 == shopInfo.getIsLock()) {
            return AjaxResult.errorResult("您的店铺已被锁定，无法上班");
        }

        //起送费
        if (null == startFree) {
            startFree = shopInfo.getStartFree();
        }

        //运费
        if (null == yunfei) {
            yunfei = shopInfo.getYunfei();
        }

        //是否提供预约
        if (null == isAppointment) {
            isAppointment = shopInfo.getIsAppointment();
        }
        //是否提供发票
        if (null == isBill) {
            isBill = shopInfo.getIsBill();
        }
        //是不是批发
        if (null == isSeriesSale) {
            isSeriesSale = shopInfo.getIsSeriesSale();
        }
        //是否自动打烊
        if (null == autoClose) {
            autoClose = shopInfo.getAutoClose();
        }
        //自动接单
        if (null == autoApply) {
            autoApply = shopInfo.getAutoApply();
        }
        //营业日期
        if (ValidateUtil.isNull(workDate)) {
            workDate = shopInfo.getWorkDate();
        }
        //可预约天数
        if (null == appointmentDate) {
            appointmentDate = shopInfo.getAppointmentDate();
        }
        //可预约时段
        if (ValidateUtil.isNull(appointmentTime)) {
            appointmentTime = shopInfo.getAppointmentTime();
        }
        if (null == affiche) {
            affiche = shopInfo.getAffiche();
        }
        //可配送天数
        if (null == appointAfterDate) {
            appointAfterDate = shopInfo.getAppointAfterDate();
        }
        //配送时段
        if (ValidateUtil.isNull(appointAfterTime)) {
            appointAfterTime = shopInfo.getAppointAfterTime();
        }

        if (null == packetPrice) {
            packetPrice = shopInfo.getPacketPrice();
        }

        //接单时间
        if (ValidateUtil.isNull(applyTime)) {
            applyTime = shopInfo.getApplyTime();
        }

        //消费自动确认时间(用户在预约时间到达后，自动确认消费)
        if (ValidateUtil.isNull(autoApplyTime)) {
            autoApplyTime = shopInfo.getApplyTime();
        }
        if (isDaoDian == null) {
            isDaoDian = shopInfo.getIsDaoDian();
        }
        if (isPeiSong == null) {
            isPeiSong = shopInfo.getIsPeiSong();
        }

        String hasMulCategoryStr = "";
        if (null != hasMulCategory) {
            hasMulCategoryStr = ",hasMulCategory=" + hasMulCategory;
        }

        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopInfo).append(" set updateUser='").append(user.getUsername()).append("',isWork=").append(isWork)
                .append(",worktime='").append(worktime).append("',startFree=").append(startFree).append(",yunfei=").append(yunfei)
//                .append(",freeYunFei=").append(freeYunFei).append(",freeYunFeiShop=").append(freeYunFeiShop).append(",freeYunFeiMoney=").append(freeYunFeiMoney)
                .append(",appointmentTime='").append(appointmentTime).append("',isAppointment=").append(isAppointment).append(",isBill=").append(isBill).append(",affiche='").append(affiche).append("'")
                .append(",isSeriesSale=").append(isSeriesSale).append(",autoClose=").append(autoClose).append(",autoApply=").append(autoApply)
                .append(",workDate='").append(workDate).append("',applyTime='").append(applyTime).append("',appointAfterTime='").append(appointAfterTime)
                .append("',appointmentDate=").append(appointmentDate).append(",appointAfterDate=").append(appointAfterDate).append(",autoApplyTime='")
                .append(autoApplyTime).append("',packetPrice=").append(packetPrice)
                .append(",isDaoDian =").append(isDaoDian)
                .append(",isPeiSong =").append(isPeiSong)
                .append(manualWorkTime)
                .append(hasMulCategoryStr)
                .append(ziQuAwardRateStr)
                .append(shareRateStr)
                .append(" where delFlag = 0 and id =").append(shopId);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //缓存更新
        ShopMemory.getInstance().modifyById(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        // 增加日志
        ShopWorkTaskUtils.createShopWorkLog(shopInfo.getId(), log_work, isWork, log_lock, shopInfo.getIsLock(), 0, user.getUsername());
        return AjaxResult.successResult();
    }


    /**
     * ---------------------------------管理员--------------------------
     */
    //获取店铺信息
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/info")
    @ResponseBody
    public String shop_info_admin(String token, Long shopId, String shopOwnUsername) {
        if (ValidateUtil.isNotID(shopId) && ValidateUtil.isNull(shopOwnUsername)) {
            return AjaxResult.errorResult("请选择店铺");
        }
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }
        ShopInfo shopInfo = null;
        if (ValidateUtil.isID(shopId)) {
            shopInfo = ShopMemory.getInstance().getShopById(shopId);
        } else {
            shopInfo = ShopMemory.getInstance().getShopByUsername(shopOwnUsername);
        }
        if (null == shopInfo) {
            return AjaxResult.successResult();
        }

        ShopInfoAndGameVO infoVO = ShopService.getInstance().getShopInfoAndGameDetailOne(user, shopInfo);
        return AjaxResult.successResult(infoVO);
    }

    //添加店铺
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/add")
    @ResponseBody
    public String shop_add(String token, ShopInfoDB info, FileUploadInfo fileUploadInfo,
                           String idCardNumber,// 店主身份证号
                           String regions,//粗略的 商圈
                           Long agentId, //精确的商圈(速达生活在用)
                           String agentIdStr, //多个商圈Id
                           String shopType,//店铺所属行业
                           String shopTips,//店铺标签
                           Integer shopTag //
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotAbsInteger(info.getShopRole())) {
            info.setShopRole(1);
        }

        if (ValidateUtil.isNull(info.getShopName())) {
            return AjaxResult.errorResult("店铺名称不能为空");
        }
        if (ValidateUtil.isNull(info.getOwnUsername())) {
            info.setOwnUsername(DateUtils.getCurrTime() + "");
//            return AjaxResult.errorResult("店主账号不能为空");
        }
        CityAgent cityAgent = null;
        if (ValidateUtil.isID(agentId)) {
            cityAgent = CityAgentMemory.getInstance().getById(agentId);
            if (null == cityAgent) {
                return AjaxResult.errorResult("代理不存在");
            }
        }

        //检查批发商个数限制
        if (null != SYS_SETTINGS.SERIES_SHOP_LIMIT_ONE_AGENT && SYS_SETTINGS.SERIES_SHOP_LIMIT_ONE_AGENT >= 0 && null != info.getIsSeriesSale() && 0 == info.getIsSeriesSale() - 1) {
            //检查该商圈下是否有批发商
            List<ShopInfo> shopList = ShopMan.listOfAgentId(agentId, 1);
            if (ValidateUtil.isAbsList(shopList) && shopList.size() >= SYS_SETTINGS.SERIES_SHOP_LIMIT_ONE_AGENT) {
                // 获取
                return AjaxResult.errorResult("所选商圈里，该类型的商家数量，已超出限制");
            }
        }

        if (ValidateUtil.isNotNull(info.getBusinessUsername())) {
            UserInfo bizUser = UserInfoMemory.getInstance().getUserInfo(info.getBusinessUsername());
            if (null == bizUser) {
                return AjaxResult.errorResult("业务员账号不存在请查证");
            }
        }
        // 平台打包费分成比例
        if (info.getPlateSharePacketRate() != null) {
            if (info.getPlateSharePacketRate() < 0.0D || info.getPlateSharePacketRate() > 100.00D) {
                info.setPlateSharePacketRate(0.0D);
            }
        }

        if (null != fileUploadInfo && null != fileUploadInfo.getShopImage()) {
            //存储图片
            String filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getShopImage());
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setImageUrl(filePath);
        }
        // 推荐图片
        if (null != fileUploadInfo && (null != fileUploadInfo.getRecomImage() || ValidateUtil.isNotNull(fileUploadInfo.getBase64RecomImg()) || ValidateUtil.isNotNull(fileUploadInfo.getRecomImageUrl()))) {
            //存储图片
            String filePath = null;
            if (fileUploadInfo.getRecomImage() != null) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getRecomImage());
            } else if (ValidateUtil.isNotNull(fileUploadInfo.getBase64RecomImg())) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64RecomImg());
            } else {
                filePath = fileUploadInfo.getRecomImageUrl();
            }
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setRecomImageUrl(filePath);
        }
        // 店铺背景图
        if (null != fileUploadInfo && (null != fileUploadInfo.getImageB() || ValidateUtil.isNotNull(fileUploadInfo.getBase64ImgB()) || ValidateUtil.isNotNull(fileUploadInfo.getImageUrlB()))) {
            //存储图片
            String filePath = null;
            if (fileUploadInfo.getImageB() != null) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getImageB());
            } else if (ValidateUtil.isNotNull(fileUploadInfo.getBase64ImgB())) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64ImgB());
            } else {
                filePath = fileUploadInfo.getImageUrlB();
            }
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setImageUrlB(filePath);
        }

        //add by qlh 2020.7.21 start
        // 店铺头像大图
        if (null != fileUploadInfo && (null != fileUploadInfo.getImage3() || ValidateUtil.isNotNull(fileUploadInfo.getBase64Img03()) || ValidateUtil.isNotNull(fileUploadInfo.getImageUrl3()))) {
            //存储图片
            String filePath = null;
            if (fileUploadInfo.getImage3() != null) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getImage3());
            } else if (ValidateUtil.isNotNull(fileUploadInfo.getBase64Img03())) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64Img03());
            } else {
                filePath = fileUploadInfo.getImageUrl3();
            }
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setImageUrlBig(filePath);
        }
        //add by qlh 2020.7.21 end

        if (0 == UserType.BUSINESS_MAN - user.getUserType()) {
            info.setBusinessUsername(user.getUsername());
        }

        // 如果一个商家属于多个商圈的话 可能会出现多个代理  此时需要进行检测

        // 所选代理检测
        if (SYS_SETTINGS.SHOP_BELONG_MULTIPLE_AGENT == 1) {
            Set<Long> agentIdSet = new HashSet<>();
            if (null != cityAgent) {
                agentIdSet.add(cityAgent.getId());
            }
            if (ValidateUtil.isNotNull(agentIdStr)) {
                Set<Long> tempSet = CommonUtils.splitToSet(agentIdStr, Long.class);
                if (tempSet != null && !tempSet.isEmpty()) {
                    agentIdSet.addAll(tempSet);
                }
            }
            SysCityAdmin sysCityAdmin = getSysCityAdminByAgentIdSet(agentIdSet, info.getCityAdmin());
            if (Optional.ofNullable(sysCityAdmin).map(SysCityAdmin::getUsername).isPresent()) {
                info.setCityAdmin(sysCityAdmin.getUsername());
            }
        }

        //v2
//        ResultInfo resultInfo = ShopMan.addShop(user.getUsername(), info, shopType, regions, idCardNumber);
        ResultInfo resultInfo = ShopMan.addShop(user.getUsername(), info, shopType, regions, idCardNumber, shopTag);
        if (resultInfo.isSuccess()) {
            Long shopId = Long.parseLong(resultInfo.getObj().toString());
            //添加店铺与代理的关系
            if (null != cityAgent) {
                ShopMan.addAgentShopRelation(cityAgent, shopId, info.getCity(), user.getUsername());

            }
            if (ValidateUtil.isNotNull(agentIdStr)) {
                ShopMan.modifyShopAgentsRelation(shopId, agentIdStr, user.getUsername());
            }

            //店铺标签联动修改
            modifyShopTip(shopId, agentId, shopTips, user.getUsername());

            return AjaxResult.successResult(resultInfo.getObj().toString());
        } else {
            return AjaxResult.errorResult(resultInfo.getError());
        }
    }

    //修改店铺
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/modify")
    @ResponseBody
    public String admin_shop_modify(String token, Long shopId, ShopInfo info, FileUploadInfo fileUploadInfo,
                                    String idCardNumber,// 店主身份证号
                                    String regions,//粗略的 商圈
                                    String shopType,//店铺所属行业
                                    String shopTips,//店铺标签
                                    Integer shopTag,
                                    Integer showOrderCounts // 基础销量(展示销量)
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (null == shopId || shopId <= 0) {
            return AjaxResult.errorResult("该选择要修改的店铺");
        }

        if (ValidateUtil.isNull(info.getShopName())) {
            return AjaxResult.errorResult("店铺名称不能为空");
        }

        //获取店铺信息
        ShopInfo shopInfoTmp = ShopMemory.getInstance().getShopById(shopId);
        if (null == shopInfoTmp) {
            return AjaxResult.errorResult("该店铺不存在，请检查后再修改");
        }
        Integer log_work = shopInfoTmp.getIsWork();
        Integer log_lock = shopInfoTmp.getIsLock();
        ShopInfo shopInfo = new ShopInfo();
        try {
            ObjectUtils.copyPropertiesExclude(shopInfoTmp, shopInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        if (ValidateUtil.isNull(info.getCity())) {
            return AjaxResult.errorResult("市不能为空");
        }

        if (User.notHasCityAuth(user.getUsername(), shopInfo.getCity(), user.getUserType())) {
            if (0 == UserType.BUSINESS_MAN - user.getUserType() && user.getUsername().equalsIgnoreCase(shopInfo.getBusinessUsername())) {
                //有权限
            } else {
                return AjaxResult.errorResult("您没有修改该城市店铺的权限");
            }
        }

        String imgeUrl = "";
        if (null != fileUploadInfo && null != fileUploadInfo.getShopImage()) {
            //存储图片
            String filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getShopImage());
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setImageUrl(filePath);

            imgeUrl = ",imageUrl = '" + filePath + "'";
        }

        // 店铺背景图
        if (null != fileUploadInfo && (null != fileUploadInfo.getImageB() || ValidateUtil.isNotNull(fileUploadInfo.getBase64ImgB()) || ValidateUtil.isNotNull(fileUploadInfo.getImageUrlB()))) {
            //存储图片
            String filePath = null;
            if (fileUploadInfo.getImageB() != null) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getImageB());
            } else if (ValidateUtil.isNotNull(fileUploadInfo.getBase64ImgB())) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64ImgB());
            } else {
                filePath = fileUploadInfo.getImageUrlB();
            }
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setImageUrlB(filePath);
            imgeUrl += ",imageUrlB='" + filePath + "'";
        }
        // 推荐图片
        if (null != fileUploadInfo && (null != fileUploadInfo.getRecomImage() || ValidateUtil.isNotNull(fileUploadInfo.getBase64RecomImg()) || ValidateUtil.isNotNull(fileUploadInfo.getRecomImageUrl()))) {
            //存储图片
            String filePath = null;
            if (fileUploadInfo.getRecomImage() != null) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getRecomImage());
            } else if (ValidateUtil.isNotNull(fileUploadInfo.getBase64RecomImg())) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64RecomImg());
            } else {
                filePath = fileUploadInfo.getRecomImageUrl();
            }
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setRecomImageUrl(filePath);
            imgeUrl += ",recomImageUrl='" + filePath + "'";
        }

        //add by qlh 2020.7.21 start
        // 店铺头像大图
        if (null != fileUploadInfo && (null != fileUploadInfo.getImage3() || ValidateUtil.isNotNull(fileUploadInfo.getBase64Img03()) || ValidateUtil.isNotNull(fileUploadInfo.getImageUrl3()))) {
            //存储图片
            String filePath = null;
            if (fileUploadInfo.getImage3() != null) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getImage3());
            } else if (ValidateUtil.isNotNull(fileUploadInfo.getBase64Img03())) {
                filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.SHOP_IMAGE, fileUploadInfo.getBase64Img03());
            } else {
                filePath = fileUploadInfo.getImageUrl3();
            }
            if (null == filePath) {
                return AjaxResult.errorResult("存储图片失败，请稍后再试");
            }
            info.setImageUrlBig(filePath);
            imgeUrl += ",imageUrlBig='" + filePath + "'";
        }
        //add by qlh 2020.7.21 end

        info.setOwnUsername(shopInfo.getOwnUsername());

        if (null != info.getLat() && info.getLat() > 0) {
            shopInfo.setLat(info.getLat());
        }
        if (null != info.getLng() && info.getLng() > 0) {
            shopInfo.setLng(info.getLng());
        }

        if (null != info.getOrderNo() && info.getOrderNo() > 0) {
            shopInfo.setOrderNo(info.getOrderNo());
        }

        // 食品安全等级
        if (null != info.getFoodSafeLevel()) {
            shopInfo.setFoodSafeLevel(info.getFoodSafeLevel());
        }
        if (null != info.getIsSelfPost()) {
            shopInfo.setIsSelfPost(info.getIsSelfPost());
        }
        if (null != info.getAppointAfterTime()) {
            shopInfo.setAppointAfterTime(info.getAppointAfterTime());
        }
        try {
            ObjectUtils.copyPropertiesExclude(info, shopInfo, null);
        } catch (Exception e) {
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        String geocode = Geohash.encode(info.getLat(), info.getLng());
        Long areaPoint = Geohash.getArea(info.getLat(), info.getLng());
        shopInfo.setGeocode(geocode);
        shopInfo.setAreaPoint(areaPoint);

        // 分成比例
        String moneyRate = "";
        if (null != info.getMoneyRate()) {
            moneyRate = ",moneyRate=" + info.getMoneyRate();
        }

        //打包费
        Double packetPrice = null != info.getPacketPrice() ? info.getPacketPrice() : 0d;

        //餐具费
        Integer hasCanJu = 0;//是否提供餐具 0不提供，1提供按订单收费，2按餐具数量收费
        Double canJuPrice = 0d;//餐具费用（1单或1套）
        if (null != info.getHasCanJu() && info.getHasCanJu() > 0) {
            hasCanJu = info.getHasCanJu();
            canJuPrice = info.getCanJuPrice();
        }

        //满足的商品金额（减运费）
        Double freeYunFei = null != info.getFreeYunFei() ? info.getFreeYunFei() : 0d;

        //需要减的配送费金额（-1时为免配送费）
        Double freeYunFeiMoney = null != info.getFreeYunFeiMoney() ? info.getFreeYunFeiMoney() : 0d;
        //减运费金额 商家承担部分
        Double freeYunFeiShop = null != info.getFreeYunFeiShop() ? info.getFreeYunFeiShop() : 0d;

        // 自动打印设置
        String autoPrint = "";
        if (ValidateUtil.isAbsInteger(info.getAutoPrint()) && (info.getAutoPrint() == 0 || info.getAutoPrint() == 1)) {
            autoPrint = " ,autoPrint=" + info.getAutoPrint() + " ";
        }
        // end
        // add by yangtk 2019年4月17日17:26:36
        String isGroupShop = "";
        if (info.getIsGroupShop() != null && (info.getIsGroupShop() == 0 || info.getIsGroupShop() == 1 || info.getIsGroupShop() == 2)) {
            isGroupShop = " ,isGroupShop = " + info.getIsGroupShop() + " ";
        }
        // end

        // 系统自动替商家接单 （即用户支付完成后，自动成为商家已接单）  1需要  0不需要
        String autoApplyBySys = "";
        if (null != info.getAutoApplyBySys()) {
            autoApplyBySys = " ,autoApplyBySys = " + info.getAutoApplyBySys() + " ";
        }
        // 不接单时需要电话通知  1需要  0不需要
        String needCall = "";
        if (null != info.getNeedCall()) {
            needCall = " ,needCall = " + info.getNeedCall() + " ";
        }

        //vr
        String vrUrl = "";
        if (null != shopInfo.getVrUrl()) {
            vrUrl = ",vrUrl = '" + shopInfo.getVrUrl() + "'";
        }
        // 是不是品牌
        String shopRoleStr = "";
        if (null != info.getShopRole()) {
            shopRoleStr = ",shopRole = " + info.getShopRole();
        }
        // 范围较大的商圈
        String lnglats1 = "";
        if (StringUtils.isNotEmpty(info.getLnglats1())) {
            lnglats1 = " ,lnglats1 = '" + info.getLnglats1() + "' ";
        }
        // 范围较小的商圈
        String lnglats2 = "";
        if (StringUtils.isNotEmpty(info.getLnglats2())) {
            lnglats2 = " ,lnglats2 = '" + info.getLnglats2() + "' ";
        }
        String cityAdminStr = "";
        if (SYS_SETTINGS.SHOP_BELONG_MULTIPLE_AGENT == 1) {
            cityAdminStr = " ,cityAdmin = '" + (info.getCityAdmin() == null ? "" : info.getCityAdmin()) + "' ";
        }
        // 对店铺的单个商品进行抽成
        String plateDrawGoodMoneyStr = "";
        if (info.getPlateDrawGoodMoney() != null) {
            plateDrawGoodMoneyStr = ",plateDrawGoodMoney = " + info.getPlateDrawGoodMoney();
        }

        //  canZhiYou; // 是否支持直邮   0普通商家，1超出配送范围可以邮寄
        String canZhiYou = "";
        if (null != info.getCanZhiYou()) {
            canZhiYou = " ,canZhiYou = " + info.getCanZhiYou() + " ";
        }
        // 自取单分成比例
        String ziShareRateStr = "";
        if (Optional.ofNullable(SYS_SETTINGS.HAS_SHOP_ZIQU_SHARE).orElse(0) - 1 == 0 && info.getZiQuShareRate() != null && info.getZiQuShareRate() >= 0) {
            ziShareRateStr = " ,ZiQuShareRate = " + info.getZiQuShareRate() + " ";
        }
        // 自取优惠比例
        String ziQuAwardRateStr = "";
        if (SYS_SETTINGS.HAS_ZIQU_AWARD == 1 && info.getZiQuAwardRate() != null && info.getZiQuAwardRate() >= 0 && info.getZiQuAwardRate() <= 100) {
            ziQuAwardRateStr += " ,ziQuAwardRate = " + info.getZiQuAwardRate();
        }
        // 团购商品分销
        String shareRateStr = "";
        if (SYS_SETTINGS.HAS_GOODS_DISTRIBUTE == 1 && info.getSharerShareRate() != null && info.getSharerShareRate() >= 0 && info.getSharerShareRate() <= 100) {
            shareRateStr += " ,sharerShareRate = " + info.getSharerShareRate();
        }

        // 税率抽成比例
        String shopTaxRateStr = "";
        if (Optional.ofNullable(SYS_SETTINGS.TAX_CALCULATION_TYPE).orElse(0) > 0 && info.getShopTaxRate() != null && info.getShopTaxRate() >= 0) {
            shopTaxRateStr = " ,shopTaxRate = " + info.getShopTaxRate() + " ";
        }
        String deliveryWorkStr = "";
        if (ValidateUtil.isNotNull(info.getDeliveryWorkDays())) {
            deliveryWorkStr = " ,deliveryWorkDays = '" + info.getDeliveryWorkDays() + "' ";
        }
        if (info.getMinCharge() != null && info.getMinCharge() >= 0) {
            deliveryWorkStr += " ,minCharge = '" + info.getMinCharge() + "' ";
        }

        String hasMulCategory = "";
        if (null != info.getHasMulCategory()) {
            hasMulCategory = ",hasMulCategory=" + info.getHasMulCategory();
        }
        // 
        String settlementTypeStr = "";
        if (info.getSettlementType() != null) {
            settlementTypeStr += ", settlementType = " + info.getSettlementType();
        }
        // 是否支持多商户同时下单
        String isSupportMuchShopOrderStr = "";
        if (info.getIsSupportMuchShopOrder() != null) {
            isSupportMuchShopOrderStr += ", isSupportMuchShopOrder = " + info.getIsSupportMuchShopOrder();
        }
        //修改
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopInfo).append(" set ")
                .append("shopName='").append(shopInfo.getShopName()).append("',telephone='").append(shopInfo.getTelephone()).append("',address='").append(shopInfo.getAddress())
                .append("',descs='").append(shopInfo.getDescs()).append("',affiche='").append(shopInfo.getAffiche())
                .append("',lng=").append(shopInfo.getLng()).append(",lat=").append(shopInfo.getLat()).append(",geocode='").append(shopInfo.getGeocode())
                .append("',areaPoint=").append(shopInfo.getAreaPoint()).append(",province='").append(shopInfo.getProvince())
                .append("',city='").append(shopInfo.getCity()).append("',county='").append(shopInfo.getCounty())
                .append("'").append(imgeUrl).append(shopRoleStr)
                .append(plateDrawGoodMoneyStr)
                .append(settlementTypeStr)
                .append(isSupportMuchShopOrderStr)
                .append(",alipay='").append(shopInfo.getAlipay()).append("',alipayRealName='").append(shopInfo.getAlipayRealName())
                .append("',tenpay='").append(shopInfo.getTenpay()).append("',tenpayopenId='").append(shopInfo.getTenpayopenId())
                .append("',worktime='").append(shopInfo.getWorktime()).append("',startFree=").append(shopInfo.getStartFree())
                .append(",freeYunFei=").append(freeYunFei).append(",freeYunFeiShop=").append(freeYunFeiShop).append(",freeYunFeiMoney=").append(freeYunFeiMoney)
                .append(",yunfei=").append(shopInfo.getYunfei()).append(",appointmentTime='").append(shopInfo.getAppointmentTime())
                .append("',isPeiSong=").append(shopInfo.getIsPeiSong()).append(",isDaoDian=").append(shopInfo.getIsDaoDian()).append(",")
                .append("isAppointment=").append(shopInfo.getIsAppointment()).append(",isWork=").append(shopInfo.getIsWork())
                .append(",isBill=").append(shopInfo.getIsBill()).append(",isSeriesSale=").append(shopInfo.getIsSeriesSale())
                .append(",isNewOpen=").append(shopInfo.getIsNewOpen()).append(",autoClose=").append(shopInfo.getAutoClose())
                .append(",autoApply=").append(shopInfo.getAutoApply()).append(",orderNo=").append(shopInfo.getOrderNo())
                .append(moneyRate).append(",ownName='").append(info.getOwnName()).append("',businessUsername='").append(info.getBusinessUsername())
                .append("',updateUser='").append(user.getUsername()).append("'")
                .append(",appointmentDate=").append(shopInfo.getAppointmentDate()).append(",appointAfterDate=").append(shopInfo.getAppointAfterDate()).append(",appointAfterTime='").append(shopInfo.getAppointAfterTime())
                .append("',foodSafeLevel='").append(shopInfo.getFoodSafeLevel()).append("'")
                .append(",isSelfPost=").append(shopInfo.getIsSelfPost()).append(autoPrint).append(isGroupShop)
                .append(",packetPrice=").append(packetPrice).append(",hasCanJu=").append(hasCanJu).append(",canJuPrice=").append(canJuPrice)
                .append(autoApplyBySys).append(needCall)
                .append(deliveryWorkStr)
                .append(canZhiYou)
                .append(ziShareRateStr)
                .append(shopTaxRateStr)
                .append(ziQuAwardRateStr)
                .append(shareRateStr)
                .append(hasMulCategory)
                .append(vrUrl)
                .append(" ,imgUpVer = 0 ")
                .append(",ownNameLang='").append(info.getOwnNameLang())
                .append("',shopNameLang='").append(info.getShopNameLang()).append("',descsLang='").append(info.getDescsLang())
                .append("',addressLang='").append(info.getAddressLang()).append("',afficheLang='").append(info.getAfficheLang()).append("',lnglats='").append(info.getLnglats()).append("'");
        // 大小电子围栏
        sb.append(lnglats1).append(lnglats2).append(cityAdminStr);
        //yang tk
        //配送固定费用修改
        if (null != info.getFixedCost() && info.getFixedCost() < 0) {
            return AjaxResult.errorResult("配送固定费用不能为负值");
        } else if (null != info.getFixedCost()) {
            sb.append(",fixedCost=").append(info.getFixedCost());
        }
        //配送固定距离
        if (null != info.getWithinDistance() && info.getWithinDistance() < 0) {
            return AjaxResult.errorResult("指定配送距离不能为负值");
        } else if (null != info.getWithinDistance()) {
            sb.append(",withinDistance=").append(info.getWithinDistance());
        }
        //超距离外单公里费用修改
        if (null != info.getOneKmCost() && info.getOneKmCost() < 0) {
            return AjaxResult.errorResult("超距离外单公里费用不能为负值");
        } else if (null != info.getOneKmCost()) {
            sb.append(",oneKmCost=").append(info.getOneKmCost());
        }
        // 平台打包费分成
        if (null != info.getPlateSharePacketRate()) {
            if (info.getPlateSharePacketRate() < 0.0D && info.getPlateSharePacketRate() > 100D) {
                return AjaxResult.errorResult("平台分成打包费设置不在范围内");
            } else {
                sb.append(",plateSharePacketRate=").append(info.getPlateSharePacketRate());
            }
        }
        // 重量
        if (null != info.getFixedWeightCost() && info.getFixedWeightCost() < 0) {
            return AjaxResult.errorResult("重量固定费不能为空");
        } else if (null != info.getFixedWeightCost()) {
            sb.append(",fixedWeightCost=").append(info.getFixedWeightCost());
        }
        // 指定重量内
        if (null != info.getWithinWeight() && info.getWithinWeight() < 0) {
            return AjaxResult.errorResult("固定重量不能为空");
        } else if (null != info.getWithinWeight()) {
            sb.append(",withinWeight=").append(info.getWithinWeight());
        }
        // 超出后
        if (null != info.getOneKgWeightCost() && info.getOneKgWeightCost() < 0) {
            return AjaxResult.errorResult("超出后每千克钱数不能为空");
        } else if (null != info.getOneKgWeightCost()) {
            sb.append(",oneKgWeightCost=").append(info.getOneKgWeightCost());
        }
        // add by yangtk 2018/10/26
        // update 预计送达所需时间
        if (null != info.getExpectDeliveryTime() && info.getExpectDeliveryTime() > 0) {
            sb.append(",expectDeliveryTime=").append(info.getExpectDeliveryTime());
        }
        // 档口编号
        if (info.getTerminal() != null) {
            sb.append(" ,terminal='").append(info.getTerminal()).append("' ");
        }
        // 支持货到付款
        if (info.getIsCashOnDelivery() != null) {
            sb.append(" , isCashOnDelivery=").append(info.getIsCashOnDelivery());
        }
        // 是否参与vip的活动
        if (info.getIsJoinVipGame() != null) {
            sb.append(" , isJoinVIPGame=").append(info.getIsJoinVipGame());
        }

        //yangtk end
        sb.append(" where id =").append(shopId).append(" and delFlag = 0 ");
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t" + sb.toString());
        //保存到数据库
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //修改店铺缓存
        ShopMemory.getInstance().modifyById(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        // 增加日志
        ShopWorkTaskUtils.createShopWorkLog(shopInfo.getId(), log_work, shopInfo.getIsWork(), log_lock, shopInfo.getIsLock(), 0, user.getUsername());
        //店铺行业关联
        //删除现有的
        ResultInfo typeResult = ShopMan.dealShopTypes(shopId, true, shopType, user.getUsername());
        if (null == typeResult) {
            return AjaxResult.errorResult("处理店铺行业失败,请稍后重试");
        } else {
            if (!typeResult.isSuccess()) {
                return AjaxResult.errorResult(typeResult.getError());
            }
        }
        //重新管理店铺对应的商圈
        ResultInfo resultInfo = ShopMan.addShopRegionRelation(shopId, regions, user.getUsername());
        if (null != resultInfo && resultInfo.isSuccess()) {

        } else {
            return AjaxResult.errorResult(resultInfo.getError());
        }

        //代理信息修改
        modifyAgent(shopInfo, user.getUsername());

        //店铺标签联动修改
        modifyShopTip(shopId, null, shopTips, user.getUsername());

        // 修改用户的身份证号
        User.modifyUserIdCardNumber(shopInfo.getOwnUsername(), idCardNumber, null);

        // 修改展示销量
        if (ValidateUtil.isAbsInteger(showOrderCounts) || shopTag != null) {
            ShopInfoExtra extra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shopId);
            if (null == extra) {

                extra = new ShopInfoExtra();
                extra.setShopId(shopId);
                extra.setOwnUsername(shopInfo.getOwnUsername());
                extra.setDelFlag(0);
                extra.setShopTag(shopTag == null ? 0 : shopTag);
                extra.setCreateUser(user.getUsername());
                extra.setCreateTime(DateUtils.getCurrTime());
                extra.setShowOrderCounts(showOrderCounts == null ? 0 : showOrderCounts);
                try {
                    UserDaoSql.getInstance().insertObj(PojoTables.SHOP_INFO_EXTRA, extra);
                } catch (SQLException e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult("修改失败，请稍后再试");
                }
            } else {
                StringBuffer sbShowCount = new StringBuffer();
//                sbShowCount.append("update ").append(PojoTables.SHOP_INFO_EXTRA).append(" set showOrderCounts=").append(showOrderCounts).append(",updateUser='").append(user.getUsername()).append("' where delFlag = 0 and shopId = ").append(shopId);
                sbShowCount.append("update ").append(PojoTables.SHOP_INFO_EXTRA).append(" set updateUser='").append(user.getUsername()).append("'");
//
                if (ValidateUtil.isAbsInteger(showOrderCounts)) {
                    sbShowCount.append(" ,showOrderCounts=").append(showOrderCounts);
                }
                if (shopTag != null) {
                    sbShowCount.append(" ,shopTag=").append(shopTag);
                }
                sbShowCount.append(" where delFlag = 0 and shopId = ").append(shopId);

                try {
                    UserDaoSql.getInstance().executeUpdateBySql(sbShowCount.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            ShopExtraInfoMemory.getInstance().addOrModify(shopId);
        }

        // 哒哒对接 - 注册门店
        ShopService.getInstance().registerOrUpdateDeliverShop(null, ShopMemory.getInstance().getShopById(shopId), true);

        return AjaxResult.successResult();
    }

    // 修改店铺的分类信息
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop-category/modify")
    @ResponseBody
    public String admin_shop_category_modify(String token, Long shopId, Integer shopCategory) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (null == shopId || shopId <= 0) {
            return AjaxResult.errorResult("该选择要修改的店铺");
        }
        if (shopCategory == null || shopCategory <= 0) {
            return AjaxResult.errorResult("请选择操作类型");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (shopInfo == null) {
            return AjaxResult.errorResult("店铺信息不存在,请核实");
        }
        if (!((shopCategory & ShopCategoryMan.shopTypeShopping) > 0 || (shopCategory & ShopCategoryMan.shopTypeGroup) > 0)) {
            return AjaxResult.errorResult("请选择操作类型2");
        }
        String sql = "update " + PojoTables.ShopInfo
                + " set updateUser ='" + user.getUsername() + "', shopCategory =" + shopCategory
                + " where delFlag = 0 and id = " + shopId;

        try {
            UserDaoSql.getInstance().executeBySql(sql);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败,请稍后重试");
        }
        ShopMemory.getInstance().modifyById(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        // 修改店铺分类信息后核对店铺的分类推荐信息
        Set<Long> shopIdSet = new HashSet<>();
        shopIdSet.add(shopId);
        return AjaxResult.successResult();
    }

    //
    @RequestMapping(method = RequestMethod.POST, value = "shop/fence/modify")
    @ResponseBody
    public String admin_shop_modify(String token, Long shopId, Integer lnglatsType) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (lnglatsType == null || (lnglatsType != FENCE_RANGE_TYPE.BIG && lnglatsType != FENCE_RANGE_TYPE.SMALL)) {
            return AjaxResult.errorResult("请选择操作类型");
        }

        // sup
        if (shopId == null) {
            StringBuilder sql = new StringBuilder();
            sql.append(" update ").append(PojoTables.ShopInfo)
                    .append(" set updateUser ='").append(user.getUsername()).append("'");
            if (lnglatsType == FENCE_RANGE_TYPE.BIG) {
                sql.append(",lnglats = lnglats1");
            } else {
                sql.append(",lnglats = lnglats2");
            }
            sql.append(" where delFlag = 0");
            if (lnglatsType == FENCE_RANGE_TYPE.BIG) {
                sql.append(" and lnglats1 is not  null and lnglats1 !=''");
            } else {
                sql.append(" and lnglats2 is not  null and lnglats2 !=''");
            }
            try {
                UserDaoSql.getInstance().executeBySql(sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult(e.getMessage());
            }
            ShopMemory.getInstance().run();
            return AjaxResult.successResult();
        } else {
            ShopInfo shop = ShopMemory.getInstance().getShopById(shopId);
            if (shop == null) {
                return AjaxResult.errorResult("未获取到店铺信息");
            }
            if (StringUtils.isNotEmpty(shop.getLnglats()) && shop.getLnglats().equals(
                    lnglatsType == FENCE_RANGE_TYPE.BIG ? shop.getLnglats1() : shop.getLnglats2())) {
                return AjaxResult.successResult();
            }
            if (StringUtils.isEmpty(lnglatsType == FENCE_RANGE_TYPE.BIG ? shop.getLnglats1() : shop.getLnglats2())) {
                return AjaxResult.errorResult("您还没有设置" + (lnglatsType == FENCE_RANGE_TYPE.BIG ? "大" : "小") + "商圈");
            }
            if (StringUtils.isNotEmpty(shop.getLnglats()) && shop.getLnglats().equals(
                    lnglatsType == FENCE_RANGE_TYPE.BIG ? shop.getLnglats1() : shop.getLnglats2())) {
                return AjaxResult.successResult();
            }
            // 不一样的
            StringBuilder sql = new StringBuilder();
            sql.append(" update ").append(PojoTables.CITY_AGENT)
                    .append(" set updateUser ='").append(user.getUsername()).append("'");
            sql.append(",lnglats = ").append(lnglatsType == FENCE_RANGE_TYPE.BIG ? "lnglats1" : "lnglats2")
                    .append(" where delFlag = 0 and id  =").append(shopId);
            try {
                UserDaoSql.getInstance().executeBySql(sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败,请稍后重试");
            }
            ShopMemory.getInstance().modify(shopId + "");
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFOS_UPDATE).setStr01(shopId + "");
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
            return AjaxResult.successResult();
        }
    }

    // 店铺创业商圈
    @RequestMapping(method = RequestMethod.POST, value = "/shop/yunfei/modify")
    @ResponseBody
    public String shop_yunfei_modify(String token, Long shopId,
                                     Integer isPeiSong, Integer isDaoDian, Integer isSelfPost,
                                     Double yunfei,
                                     Double startFree,
                                     Double freeYunFei, Double freeYunFeiShop, Double freeYunFeiMoney,
                                     Double fixedCost, Double withinDistance, Double oneKmCost,
                                     Double fixedWeightCost, Double oneKgWeightCost, Double withinWeight) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (null == shopId || shopId <= 0) {
            return AjaxResult.errorResult("该选择要修改的店铺");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (null == shopInfo) {
            return AjaxResult.errorResult("店铺信息不存在，请查证");
        }
        // 店铺承担的  = 减免的
        freeYunFeiShop = freeYunFeiMoney;
        ResultInfo resultInfo = ShopMan.shopModifyYunfei(shopInfo, isPeiSong, isDaoDian, isSelfPost,
                yunfei,
                startFree,
                freeYunFei, freeYunFeiShop, freeYunFeiMoney,
                fixedCost, withinDistance, oneKmCost,
                fixedWeightCost, oneKgWeightCost, withinWeight, user.getUsername());
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        return AjaxResult.successResult();
    }

    // 修改运费
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/yunfei/modify")
    @ResponseBody
    public String admin_shop_yunfei_modify(String token, Long shopId,
                                           Integer isPeiSong, Integer isDaoDian, Integer isSelfPost,
                                           Double yunfei,
                                           Double startFree,
                                           Double freeYunFei, Double freeYunFeiShop, Double freeYunFeiMoney,
                                           Double fixedCost, Double withinDistance, Double oneKmCost,
                                           Double fixedWeightCost, Double oneKgWeightCost, Double withinWeight
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (null == shopInfo) {
            return AjaxResult.errorResult("店铺信息不存在，请查证");
        }
        ResultInfo resultInfo = ShopMan.shopModifyYunfei(shopInfo, isPeiSong, isDaoDian, isSelfPost,
                yunfei,
                startFree,
                freeYunFei, freeYunFeiShop, freeYunFeiMoney,
                fixedCost, withinDistance, oneKmCost,
                fixedWeightCost, oneKgWeightCost, withinWeight, user.getUsername());
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }
        return AjaxResult.successResult();
    }

    //查看店铺所属行业
    //修改店铺行业
    @RequestMapping(method = RequestMethod.POST, value = "/shop/type/relation")
    @ResponseBody
    public String admin_shop_type(String token, Long shopId, String typeId) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有修改权限");
        }


        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("该选择要修改的店铺");
        }

        if (ValidateUtil.isNull(typeId)) {
            return AjaxResult.errorResult("店铺行业不能为空");
        }


        //删除原有的
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopTypeRelation).append(" set updateUser='").append(user.getUsername())
                .append("',delFlag=1 where delFlag = 0 and shopId in (").append(shopId).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //添加为新的
        Long time = DateUtils.getCurrTime();
        String[] types = typeId.split(",");
        for (int i = 0; i < types.length; i++) {
            if (ValidateUtil.isNull(types[i])) {
                continue;
            }
            ShopTypeRelation typeInfo = new ShopTypeRelation(shopId, Integer.parseInt(types[i]), user.getUsername(), time);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.ShopTypeRelation, typeInfo);
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("修改失败，请稍后再试");
            }
        }

        //缓存更新
        ShopTypeRelationMemory.getInstance().modifyByShopId(shopId);

        return AjaxResult.successResult();
    }

    //设置店铺是否为推荐 (猜你喜欢）
    @RequestMapping(method = RequestMethod.POST, value = "/shop/recommend/add")
    @ResponseBody
    public String admin_shop_recommend(String token, Long shopId, Integer isRecommend, Integer isGroup) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("该选择要修改的店铺");
        }

        if (null == isRecommend) {
            isRecommend = 0;
        }
        String isRecommendStr = "";
        if (SYS_SETTINGS.DISTINGUISH_SHOP_RECOMMEND == 1) {
            if (isGroup != null && isGroup == 1) {
                isRecommendStr = ",isRecommend2 = " + isRecommend;
            } else if (isGroup != null && isGroup > 1) {
                isRecommendStr = ",isRecommend = " + isRecommend + ",isRecommend2 = " + isRecommend;
            } else {
                isRecommendStr = ",isRecommend = " + isRecommend;
            }
        } else {
            isRecommendStr = ",isRecommend = " + isRecommend;
        }

        StringBuilder sb = new StringBuilder();
        // sb.append("update ").append(PojoTables.ShopInfo).append(" set updateUser='").append(user.getUsername()).append("',isRecommend=").append(isRecommend).append(" where delFlag = 0 and id in (").append(shopId).append(")");
        sb.append("update ").append(PojoTables.ShopInfo).append(" set updateUser='").append(user.getUsername()).append("' ").append(isRecommendStr).append(" where delFlag = 0 and id in (").append(shopId).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //缓存更新
        ShopMemory.getInstance().modifyById(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        return AjaxResult.successResult();
    }

    // 设置店铺或者关闭店铺为优选店铺
    @RequestMapping(method = RequestMethod.POST, value = "/shop/isPreference/update")
    @ResponseBody
    public String admin_shop_preference(String token, Long shopId, Integer isGroup, Integer isPreference) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("该选择要修改的店铺");
        }

        if (null == isPreference || (isPreference != 0 && isPreference != 1)) {
            return AjaxResult.errorResult("操作类型不正确");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (shopInfo == null) {
            return AjaxResult.errorResult("店铺信息不存在,请核实");
        }
//        if (shopInfo.getIsPreference() == isPreference) {
//            return AjaxResult.successResult();
//        }
        String isPreferenceStr = "";
        if (SYS_SETTINGS.DISTINGUISH_SHOP_RECOMMEND == 1) {
            if (isGroup != null && isGroup == 1) {
                isPreferenceStr = ",isPreference2 = " + isPreference;
            } else if (isGroup != null && isGroup > 1) {
                isPreferenceStr = ",isRecommend = " + isPreference + ",isPreference2 = " + isPreference;
            } else {
                isPreferenceStr = ",isPreference = " + isPreference;
            }
        } else {
            isPreferenceStr = ",isPreference = " + isPreference;
        }

        StringBuilder sb = new StringBuilder();
//        sb.append("update ").append(PojoTables.ShopInfo).append(" set updateUser='").append(user.getUsername()).append("',isPreference=").append(isPreference).append(" where delFlag = 0 and id in (").append(shopId).append(")");
        sb.append("update ").append(PojoTables.ShopInfo).append(" set updateUser='").append(user.getUsername()).append("' ").append(isPreferenceStr).append(" where delFlag = 0 and id in (").append(shopId).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }
        //缓存更新
        ShopMemory.getInstance().modifyById(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }


    //设置店铺是不是配送或到店消费
    @RequestMapping(method = RequestMethod.POST, value = "/shop/peisong/daodian")
    @ResponseBody
    public String admin_shop_daodian(String token, String shopId, Integer isDaoDian, Integer isPeiSong) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(shopId)) {
            return AjaxResult.errorResult("该选择要修改的店铺");
        }

        if (null == isDaoDian) {
            isDaoDian = 0;
        }
        if (null == isPeiSong) {
            isPeiSong = 0;
        }

        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopInfo).append(" set updateUser='").append(user.getUsername()).append("',isDaoDian=").append(isDaoDian).append(",isPeiSong=").append(isPeiSong)
                .append(" where delFlag = 0 and id in (").append(shopId).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //缓存更新
        ShopMemory.getInstance().modify(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFOS_UPDATE).setStr01(shopId + "");
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }

    //删除店铺
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/delete")
    @ResponseBody
    public String shop_delete(String token, String shopId) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
//        if (0 != user.getUserType() - UserType.ADMIN) {
//            return AjaxResult.errorResult("您没有操作权限");
//        }
        if (ValidateUtil.isNull(shopId)) {
            return AjaxResult.errorResult("请选择要删除的店铺");
        }

        //删除店铺
        ResultInfo resultInfo = ShopMan.deleteShop(shopId, user.getUsername(), user.getUserType());
        if (null == resultInfo) {
            return AjaxResult.errorResult("删除失败，请稍后再试");
        } else {
            if (!resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo.getError());
            }
        }
        return AjaxResult.successResult();
    }


    // 设置为优选商家
    //设置店铺是否为推荐 (猜你喜欢）
    @RequestMapping(method = RequestMethod.POST, value = "/shop/isPreference/add-cal")
    @ResponseBody
    public String admin_shop_isPreference_add_cal(String token, Long shopId, Integer isPreference) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("该选择要修改的店铺");
        }
        if (null == isPreference) {
            return AjaxResult.errorResult("请选择操作类型");
        }
        if (isPreference != 0 && isPreference != 1) {
            return AjaxResult.errorResult("未知的操作类型");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (shopInfo == null) {
            return AjaxResult.errorResult("未获取到商家信息");
        }
        if (shopInfo.getIsPreference() == isPreference) {
            return AjaxResult.successResult();
        }
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopInfo).append(" set updateUser='").append(user.getUsername()).append("',isPreference=").append(isPreference).append(" where delFlag = 0 and id in (").append(shopId).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }
        //缓存更新
        ShopMemory.getInstance().modifyById(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }


    //------------------------------------------------启用、停用店铺
    //停用启用店铺
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/lock")
    @ResponseBody
    public String shop_lock(String token, Long shopId, Integer isLock, Integer isWork) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get
                (token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("店铺不能为空");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (shopInfo == null) {
            return AjaxResult.errorResult("店铺不存在");
        }
//        if (ValidateUtil.isAbsInteger(isLock) || ((isLock != 1) && (isLock != 0))) {
//            return AjaxResult.errorResult("请确认停用还是启用");
//        }
        if (0 == isLock) {
            isWork = 0;
        }
        Integer log_work = shopInfo.getIsWork();
        Integer log_lock = shopInfo.getIsLock();


        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.ShopInfo).append(" set isLock = ").append(isLock)
                .append(",isWork = ").append(isWork)
                .append(",updateUser = '").append(user.getUsername())
                .append("' where delFlag = 0").append(" and id = ").append(shopId);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("停用/启用店铺失败，请稍后再试");
        }

        //缓存更新
        ShopMemory.getInstance().modifyById(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        // 增加日志
        ShopWorkTaskUtils.createShopWorkLog(shopInfo.getId(), log_work, isWork, log_lock, isLock, 0, user.getUsername());
        // 锁定商户
        if (SYS_SETTINGS.LOCK_SHOP_IS_LOCK_USER != null && SYS_SETTINGS.LOCK_SHOP_IS_LOCK_USER == 1) {
            if (isLock == 1) {
                isLock = 0;
            } else {
                isLock = 1;
            }
            ResultInfo resultInfo = UserManagerAction.lockUser(user.getUsername(), shopInfo.getOwnUsername(), isLock);
            if (resultInfo != null && resultInfo.isSuccess()) {
                if (isLock == 1) {
                    // 将用户token剔除
                    MemcacheUtil.removeByUsername(shopInfo.getOwnUsername()); // 删除token
                }
            }
        }
        return AjaxResult.successResult();
    }


    //一键上下班/停启所有店铺（根据城市/商圈）
    @RequestMapping(method = RequestMethod.POST, value = "/admin/allShop/status/modify")
    @ResponseBody
    public String all_shop_lock(String token, String city, Long agentId, Integer isLock, Integer isWork,
                                Integer isCityAgent  //   //是否按代理获取 0否 1是
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("城市不能为空");
        }

        StringBuilder sb = new StringBuilder();

        // 根据代理账号获取店铺Id
        List<Long> shopIdList = null;
        String shopIds = null;
        if (null != isCityAgent && isCityAgent - 1 == 0) {
            shopIdList = OrderListMan.getShopIdList(user.getUsername());
            shopIds = JSON.toJSONString(shopIdList);
            shopIds = shopIds.replace("[", "").replace("]", "");
        }


        boolean isUpdateLock = false;

        //  1 一键上下班(针对解锁的)
        if (ValidateUtil.isAbsInteger(isWork)) {
            sb.append("update ").append(PojoTables.ShopInfo).append(" set isWork = ").append(isWork)
                    .append(",manualWorkTime=").append(DateUtils.getCurrTime())
                    .append(",updateUser = '").append(user.getUsername())
                    .append("' where delFlag = 0").append(" and city = '").append(city).append("' and isLock = 1")
                    .append(ValidateUtil.isNull(shopIds) ? "" : " and id in (" + shopIds + ")");
        }

        //1 一键锁定---下班状态    2 一键解锁
        if (ValidateUtil.isAbsInteger(isLock)) {
            isUpdateLock = true;
            if (0 == isLock) { // 0 isLock 锁定---下班
                isWork = 0;
            }
            if (1 == isLock) {
                isWork = 0;
            }
            sb.append("update ").append(PojoTables.ShopInfo).append(" set isLock = ").append(isLock)
                    .append(",isWork = ").append(isWork)
                    .append(",updateUser = '").append(user.getUsername())
                    .append("' where delFlag = 0").append(" and city = '").append(city).append("'")
                    .append(ValidateUtil.isNull(shopIds) ? "" : " and id in (" + shopIds + ")");
        }

        if (0 == UserType.BUSINESS_MAN - user.getUserType()) {
            sb.append(" and businessUsername='").append(user.getUsername()).append("'");
        }
        List<ShopInfo> modifyValidShopList = listOfShopInfoByCity(shopIdList, city, isUpdateLock);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("一键停用/启用店铺失败，请稍后再试");
        }

        //在缓存中更新
        ShopMemory.getInstance().modifyV2(city);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFOS_UPDATE_BY_CITY).setStr01(city);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        // 添加商家上下班日志
        createShopLog(modifyValidShopList, isUpdateLock, isWork, isUpdateLock ? isLock : 1, user.getUsername());
        return AjaxResult.successResult();
    }

    // 添加日志信息
    private void createShopLog(List<ShopInfo> list, boolean isUpdateLock, Integer afterWork, Integer afterLock, String opUser) {
        if (!ValidateUtil.isAbsList(list)) {
            return;
        }
        for (ShopInfo shopInfo : list) {
            if (isUpdateLock) {
                ShopWorkTaskUtils.createShopWorkLog(shopInfo.getId(), shopInfo.getIsWork(), 0, shopInfo.getIsLock(), afterLock, 0, opUser);
            } else {
                ShopWorkTaskUtils.createShopWorkLog(shopInfo.getId(), shopInfo.getIsWork(), afterWork, shopInfo.getIsLock(), afterLock, 0, opUser);
            }
        }
    }

    private List<ShopInfo> listOfShopInfoByCity(List<Long> shopIdList, String city, boolean isUpdateLock) {
        if (!ValidateUtil.isAbsList(shopIdList) && ValidateUtil.isNull(city)) {
            return Collections.emptyList();
        }
        List<ShopInfo> list = new ArrayList<>();
        if (ValidateUtil.isAbsList(shopIdList)) {
            Set<Long> set = new HashSet<>(shopIdList);
            for (Long shopId : set) {
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
                if (shopInfo != null) {
                    if (!isUpdateLock && shopInfo.getIsLock() == 1) {
                        list.add(shopInfo);
                    } else if (isUpdateLock) {
                        list.add(shopInfo);
                    }
                }
            }
        } else {
            StringBuffer sql = new StringBuffer();
            sql.append("select * from ").append(PojoTables.ShopInfo)
                    .append(" where delFlag = 0 and city ='")
                    .append(city).append("'");
            if (!isUpdateLock) {
                sql.append(" and isLock =1");
            }
            try {
                list = (List<ShopInfo>) UserDaoSql.getInstance().list(ShopInfo.class, sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ValidateUtil.isAbsList(list) ? list : Collections.emptyList();
    }


    /**
     * ------------------------------------------------评价
     */
    //管理员获取所有评价信息
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/comment/list")
    @ResponseBody
    public String recommend_admin_list(String token, Long shopId, String orderNo, Long startTime, Long endTime, Integer rateType, // 评论类型 1. 差评 2 中评 3.好评
                                       Integer isReply, // 是否回复
                                       Integer serviceRateType, // 服务 1. 差评 2 中评 3.好评
                                       Integer deliveryRateType, // 配送 1. 差评 2 中评
                                       Integer verifyState,     // 审核状态
                                       Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有访问权限");
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        String sqlList = "SELECT sc.* , OI.createTime as orderCreateTime ";
        String sqlCount = "SELECT count(1) counts  from ( select sc.*";
        String sql = "FROM " + PojoTables.ShopComment + " sc " +
                "JOIN " + PojoTables.ShopInfo + " si ON si.Id = sc.shopId AND (si.shopCategory&" + ShopCategoryMan.shopTypeShopping + ")>0 " +
                (user.getUserType() == UserType.ADMIN ?
                        ("LEFT JOIN " + PojoTables.SHOP_AGENT_RELATION + " sar ON sar.shopId = sc.shopId AND sar.delFlag=0 " +
                                "LEFT JOIN " + PojoTables.USER_AGENT_RELATION + " uar ON uar.agentId = sar.agentId AND uar.delFlag=0 ")
                        : "") +
                "LEFT JOIN " + PojoTables.OrderInfo + " OI ON OI.orderNo = sc.orderNo AND OI.delFlag=0 " +
                "WHERE sc.delFlag=0 ";
        if (verifyState != null && verifyState != 0) {
            sql += " and sc.verifyState =" + verifyState;
        }
//        and uar.username=20180901001
        if (ValidateUtil.isID(shopId)) {
            sql += " and sc.shopId=" + shopId + " ";
        }
        if (null != rateType && rateType > 0) {
            String rateTypeStr = "";
            if (rateType == 1) {
                rateTypeStr = "1, 2";
            } else if (rateType == 2) {
                rateTypeStr = "3";
            } else if (rateType == 3) {
                rateTypeStr = "4, 5";
            }
            sql += " and sc.star in (" + rateTypeStr + ") ";
        }
        if (null != serviceRateType && serviceRateType > 0) {
            if (serviceRateType == 1) {
                sql += " and sc.serviceStar < 3 ";
            } else if (serviceRateType == 2) {
                sql += " and sc.serviceStar = 3 ";
            } else if (serviceRateType == 3) {
                sql += " and sc.serviceStar > 3 ";
            }
        }
        if (null != deliveryRateType && deliveryRateType > 0) {
            if (deliveryRateType == 1) {
                sql += " and sc.deliveryStar < 3 ";
            } else if (deliveryRateType == 2) {
                sql += " and sc.deliveryStar = 3 ";
            } else if (deliveryRateType == 3) {
                sql += " and sc.deliveryStar > 3 ";
            }
        }
        if (null != isReply && isReply > 0) {
            sql += " and sc.extra1=" + (isReply == 1 ? Expression.OP_ISNULL : Expression.OP_ISNOTNULL) + " ";
        }
        if (ValidateUtil.isNotNull(orderNo)) {
            sql += " and sc.orderNo=" + orderNo + " ";
        }
        if (ValidateUtil.isAbsLong(startTime)) {
            sql += " and sc.createTime >=" + startTime + " ";
        }
        if (ValidateUtil.isAbsLong(endTime)) {
            sql += " and sc.createTime <=" + endTime + " ";
        }
        if (user.getUserType() == UserType.ADMIN) {
            sql += " and uar.username='" + user.getUsername() + "' ";
        }

        sql += " GROUP BY orderno  ";
        String sqlOrder = " order by createTime desc";
        String sqlLimit = " limit " + (page - 1) * size + "," + size;


        sqlCount = sqlCount + sql + ") a ";
        List<ShopCommentInfoVO> list = null;
        Long totalCount = 0l;
        try {
            if (!isNoCount) {
                totalCount = UserDaoSql.getInstance().getCount(sqlCount);
            }
            if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                list = (List<ShopCommentInfoVO>) UserDaoSql.getInstance().list(ShopCommentInfoVO.class, sqlList + sql + sqlOrder + sqlLimit);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("评论获取失败，请稍后再试");
        }

        if (ValidateUtil.isAbsList(list)) {
            List<ShopCommentInfoVO> voList = new ArrayList<ShopCommentInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                ShopCommentInfoVO infoVO = list.get(i);
                if (null == infoVO) {
                    continue;
                }
                if (ValidateUtil.isID(infoVO.getShopId())) {
                    ShopInfo shopInfo = ShopMemory.getInstance().getShopById(infoVO.getShopId());
                    if (null != shopInfo) {
                        ShopInfoVO shopInfoVO = new ShopInfoVO();
                        BeanUtils.copyProperties(shopInfo, shopInfoVO);
                        infoVO.setShopInfo(shopInfoVO);
                    }
                }

                if (0 == 1 - infoVO.getIsUnknownName()) {
                    infoVO.setCreateUser("");
                    infoVO.setSignPhoto("");
                    infoVO.setName("");
                } else {
                    if (ValidateUtil.isNotNetUrl(infoVO.getSignPhoto())) {
                        infoVO.setSignPhoto(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getSignPhoto());
                    }
                }
                if (ValidateUtil.isNotNetUrl(infoVO.getImage1Url())) {
                    infoVO.setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage1Url());
                }
                if (ValidateUtil.isNotNetUrl(infoVO.getImage2Url())) {
                    infoVO.setImage2Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage2Url());
                }
                if (ValidateUtil.isNotNetUrl(infoVO.getImage3Url())) {
                    infoVO.setImage3Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage3Url());
                }
                if (ValidateUtil.isNotNetUrl(infoVO.getImage4Url())) {
                    infoVO.setImage4Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage4Url());
                }
                voList.add(infoVO);
            }
            return AjaxResult.successResult(totalCount, voList.size(), voList);
        }

        return AjaxResult.successResult(0, 0, null);
    }


    @RequestMapping(method = RequestMethod.POST, value = "/shop/comment/del")
    @ResponseBody
    public String shop_comment_del(String token, Long id) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (id == null) {
            return AjaxResult.errorResult("评论id不能为空");
        }
        StringBuilder SELsql = new StringBuilder();
        SELsql.append(" select * from ").append(PojoTables.ShopComment).append(" where delFlag = 0").append(" and id =").append(id);
        ShopCommentInfo shopCommentInfo = null;
        try {
            shopCommentInfo = (ShopCommentInfo) UserDaoSql.getInstance().getObject(ShopCommentInfo.class, SELsql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败");
        }
        if (shopCommentInfo == null) {
            return AjaxResult.errorResult("评论信息不存在,请核实");
        }
        StringBuilder delSql = new StringBuilder();
        delSql.append("update ").append(PojoTables.ShopComment).append(" set delFlag =1 ").append(" where id =").append(id).append(" and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(delSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败,请稍后重试");
        }
        return AjaxResult.successResult();
    }

    // 商家获取评论信息
    @RequestMapping(method = RequestMethod.POST, value = "/list/shop/comment")
    @ResponseBody
    public String get_comment_list(String token, Long startTime, Long endTime, Integer isUnKnownName, Integer page, Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null || size < 1) {
            size = 20;
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (shopInfo == null) {
            return AjaxResult.successResult(0, 0, null);
        }
        StringBuilder sql = new StringBuilder();
        sql.append("select * from ").append(PojoTables.ShopComment).append(" where delFlag = 0").append(" and shopId =").append(shopInfo.getId());

        if (isUnKnownName != null && (isUnKnownName == 1 || isUnKnownName == 0)) {
            sql.append(" and isUnKnownName=").append(isUnKnownName);
        }
        if (startTime != null) {
            sql.append(" and createTime >").append(startTime);
        }
        if (endTime != null) {
            sql.append(" and createTime <").append(endTime);
        }
        sql.append(" order By createTime desc");
        List<ShopCommentInfo> list = null;
        try {
            list = (List<ShopCommentInfo>) UserDaoSql.getInstance().list(ShopCommentInfo.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败,请稍后重试");
        }
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(0, 0, null);
        }
        JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
        List<ShopCommentInfoVO> resultList = new ArrayList<>();
        for (ShopCommentInfo commentInfo : (List<ShopCommentInfo>) pageList.list) {
            ShopCommentInfoVO infoVO = new ShopCommentInfoVO();
            try {
                ObjectUtils.copyPropertiesExclude(commentInfo, infoVO, null);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            if (null == infoVO) {
                continue;
            }
            if (0 == 1 - infoVO.getIsUnknownName()) {
                infoVO.setCreateUser("");
                infoVO.setSignPhoto("");
                infoVO.setName("");
            } else {
                if (ValidateUtil.isNotNetUrl(infoVO.getSignPhoto())) {
                    infoVO.setSignPhoto(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getSignPhoto());
                }
            }
            if (ValidateUtil.isNotNetUrl(infoVO.getImage1Url())) {
                infoVO.setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage1Url());
            }
            if (ValidateUtil.isNotNetUrl(infoVO.getImage2Url())) {
                infoVO.setImage2Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage2Url());
            }
            if (ValidateUtil.isNotNetUrl(infoVO.getImage3Url())) {
                infoVO.setImage3Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage3Url());
            }
            if (ValidateUtil.isNotNetUrl(infoVO.getImage4Url())) {
                infoVO.setImage4Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getImage4Url());
            }
            resultList.add(infoVO);
        }
        return AjaxResult.successResult(pageList.totalCount, resultList.size(), resultList);
    }

    // 商家回复评论信息
    @RequestMapping(method = RequestMethod.POST, value = "/shop/comment/reply")
    @ResponseBody
    public String get_comment_list(String token, Long id, String reply) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (id == null) {
            return AjaxResult.errorResult("评论id不能为空");
        }
        if (ValidateUtil.isNull(reply)) {
            return AjaxResult.errorResult("请输入回复的内容");
        }
        StringBuilder SELsql = new StringBuilder();
        SELsql.append(" select * from ").append(PojoTables.ShopComment).append(" where delFlag = 0").append(" and id =").append(id);
        ShopCommentInfo shopCommentInfo = null;
        try {
            shopCommentInfo = (ShopCommentInfo) UserDaoSql.getInstance().getObject(ShopCommentInfo.class, SELsql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败");
        }
        if (shopCommentInfo == null) {
            return AjaxResult.errorResult("评论信息不存在,请核实");
        }
        StringBuilder delSql = new StringBuilder();

        delSql.append("update ").append(PojoTables.ShopComment).append(" set extra1 = '").append(reply).append("'")
                .append(",updateUser='").append(user.getUsername()).append("'")
                .append(" where id =").append(id).append(" and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(delSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败,请稍后重试");
        }
        return AjaxResult.successResult();
    }


    //修改店铺信息 的时候  代理信息联动
    private boolean modifyAgent(ShopInfo shopInfo, String opUsername) {
        //代理信息联动修改
        if (ValidateUtil.isAbsInteger(SYS_SETTINGS.AGENT_IS_SHOP) && 0 == 1 - SYS_SETTINGS.AGENT_IS_SHOP) {
            CityAgent cityAgent = CityAgentMemory.getInstance().getByUsername(shopInfo.getOwnUsername());
            if (null != cityAgent) {

                //修改代理信息
                StringBuffer s = new StringBuffer();
                s.append("update ").append(PojoTables.CITY_AGENT).append(" set name='").append(shopInfo.getShopName()).append("',address='").append(shopInfo.getAddress())
                        .append("',updateUser='").append(opUsername).append("',lat=").append(shopInfo.getLat()).append(",lng=").append(shopInfo.getLng())
                        .append(",geocode='").append(shopInfo.getGeocode()).append("',areaPoint=").append(shopInfo.getAreaPoint()).append(" where delFlag = 0 and id = ")
                        .append(cityAgent.getId());

                try {
                    UserDaoSql.getInstance().executeBySql(s.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("修改店铺信息时，更新代理信息错误" + e.getMessage());
                }
                CityAgentMemory.getInstance().modify(cityAgent.getId());
                // 数据同步
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_CITY_UPDATE).setLong01(cityAgent.getId());
                JmsSender.setTopicSender(notify);
            }
        }

        return true;
    }

    //修改店铺信息 的时候  标签联动
    private void modifyShopTip(Long shopId, Long agentId, String tips, String opUsername) {
        //代理信息联动修改
        if (ValidateUtil.isNull(tips)) {
            return;
        }
        if (null == shopId) {
            return;
        }

        //先去除之前的的标签，然后加上现在的
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.SHOP_TIP_RELATION).append(" set delFlag = 1,updateUser='").append(opUsername).append("' where shopId = ").append(shopId);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //获取店铺关联的代理
        if (ValidateUtil.isNotID(agentId)) {
            agentId = ShopAgentRelationMemory.getInstance().getAgentByShopId(shopId);
        }

        //保存标签关联关系
        String[] typs = tips.split(",");
        if (null != typs & typs.length > 0) {
            long time = DateUtils.getCurrTime();
            for (int i = 0; i < typs.length; i++) {
                if (ValidateUtil.isNull(typs[i])) {
                    continue;
                }
                try {
                    ShopTipRelation shopTipRelation = new ShopTipRelation();
                    shopTipRelation.setShopId(shopId);
                    shopTipRelation.setAgentId(agentId);
                    shopTipRelation.setShopTipId(Long.parseLong(typs[i]));

                    shopTipRelation.setCreateTime(time);
                    shopTipRelation.setCreateUser(opUsername);
                    shopTipRelation.setDelFlag(0);
                    shopTipRelation.setOrderNo(0);
                    try {
                        UserDaoSql.getInstance().insertObj(PojoTables.SHOP_TIP_RELATION, shopTipRelation);
                    } catch (SQLException e) {
                        e.printStackTrace();
                        continue;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
        //店铺关联行业添加缓存
        ShopTipRelationMemory.getInstance().load();
        // 数据同步
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_TIP_RELATION_RELOAD);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        return;
    }

    // 根据代理获取商家上代理信息
    private SysCityAdmin getSysCityAdminByAgentIdSet(Set<Long> agentIdSet, String username) {
        if (agentIdSet == null || agentIdSet.isEmpty()) {
            return null;
        }
        List<SysCityAdmin> list = new ArrayList<>();
        for (Long id : agentIdSet) {
            List<String> adminUsernameList = UserAgentRelationMemory.getInstance().usernameListOfAgentId(id);
            if (adminUsernameList != null && adminUsernameList.isEmpty()) {
                SysCityAdmin admin = getByCityAdminUsername(adminUsernameList.get(0));
                if (null != admin) {
                    list.add(admin);
                }
            }
        }
        SysCityAdmin sysCityAdmin = null;
        if (list != null && !list.isEmpty()) {
            if (!StringUtils.isEmpty(username)) {
                for (SysCityAdmin sys : list) {
                    if (Optional.ofNullable(sys).map(SysCityAdmin::getUsername).isPresent() && username.equals(sys.getUsername())) {
                        sysCityAdmin = sys;
                        break;
                    }
                }
            } else {
                sysCityAdmin = list.get(0);
            }
        }
        return sysCityAdmin;
    }

    // 获取一个代理信息
    public static SysCityAdmin getByCityAdminUsername(String username) {
        return null;
    }

    // 同步商家信息   。。。。。。。
    @RequestMapping(value = "admin/batch/shop/synch", method = RequestMethod.POST)
    @ResponseBody
    public String synch_shop_info_batch(String token, Long baseShopId, String shopIds, Integer isSynchAllShop, Integer isSynchAffiche, Integer isSynchDelivery, Integer isSynchDescs, Integer isSynchOpen) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (baseShopId == null || baseShopId <= 0) {
            return AjaxResult.errorResult("请选择基础店铺");
        }
        ShopInfo baseShopInfo = ShopMemory.getInstance().getShopById(baseShopId);
        if (baseShopInfo == null) {
            return AjaxResult.errorResult("未获取到基础商家信息");
        }
        if ((isSynchAffiche == null || isSynchAffiche == 0)
                && (isSynchDelivery == null || isSynchDelivery == 0)
                && (isSynchDescs == null || isSynchDescs == 0)
                && (isSynchOpen == null || isSynchOpen == 0)) {
            return AjaxResult.errorResult("请选择同步的信息");
        }
        if (StringUtils.isNotEmpty(shopIds)) {
            if (StringUtils.split(shopIds, ",").length == 0) {
                return AjaxResult.errorResult("请选择同步的店铺");
            }
        } else if (isSynchAllShop != null && isSynchAllShop == 1) {
            List<ShopInfo> shopInfos = ShopMemory.getInstance().list();
            if (shopInfos == null || shopInfos.size() == 0) {
                return AjaxResult.successResult();
            }
            Set<Long> shopIdSet = new HashSet<>();
            for (ShopInfo shopInfo : shopInfos) {
                if (shopInfo == null) {
                    continue;
                }
                shopIdSet.add(shopInfo.getId());
            }
            shopIds = StringUtils.join(shopIdSet, ",");
        }
        if (StringUtils.isEmpty(shopIds)) {
            return AjaxResult.errorResult("请选择需要同步的店铺");
        }
        // 同步店铺信息
        try {
            ShopMan.batchShopSynch(baseShopInfo, shopIds, user.getUsername(), (isSynchAffiche != null && isSynchAffiche == 1 ? true : false), (isSynchDelivery != null && isSynchDelivery == 1 ? true : false)
                    , (isSynchDescs != null && isSynchDescs == 1 ? true : false), (isSynchOpen != null && isSynchOpen == 1 ? true : false));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("同步失败,请稍后重试");
        }
        // 成功
        return AjaxResult.successResult();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/admin/group/shop/comment/list")
    @ResponseBody
    public String recommend_groupshop_list(String token, String city, String county, Long shopId, Long startTime, Long endTime, Integer rateType, // 评论类型 1. 全部 2 高分 3.低分
                                           Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有访问权限");
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        String timeStr = "";
        if (null != startTime && null != endTime) {
            timeStr = " and sc.createTime >= " + startTime + " and sc.createTime <= " + endTime;
        }
        String shop = "";
        if (null != shopId) {
            shop = " and sc.shopId=" + shopId + " ";
        }
        String usern = "";
        if (user.getUserType() == UserType.ADMIN) {
            usern = " and uar.username=" + user.getUsername() + " ";
        }
        String rate = "";
        if (null != rateType) {
            switch (rateType) {
                case 2:
                    rate = " and sc.star > 3 ";
                    break;
                case 3:
                    rate = " and sc.star <= 3";
            }
        }
        String cityStr = "";
        if (ValidateUtil.isNotNull(city)) {
            cityStr += " and si.city ='" + city + "' ";
        }
        if (ValidateUtil.isNotNull(county)) {
            cityStr += " and si.county ='" + county + "' ";
        }
        String sql = " FROM shop_comment sc " +
                "LEFT JOIN order_info ori ON sc.orderNO = ori.orderNo AND ori.delFlag=0 " +
                "LEFT JOIN shop_info si ON si.id = sc.shopId AND si.delFlag=0 " +
                "LEFT JOIN shop_agent_relation sar ON sar.shopId = si.id AND sar.delFlag=0 " +
                "LEFT JOIN user_agent_relation uar ON uar.agentId = sar.agentId AND uar.delFlag=0 " +
                "WHERE sc.delFlag=0 AND (si.shopCategory & " + ShopCategoryMan.shopTypeGroup + ") > 0 " + timeStr + shop + rate + usern + cityStr + " " +
                "Order By sc.createTime desc ";
        String listSql = " SELECT sc.*,si.shopName,ori.createTime AS orderCreateTime ";
        String countSql = " SELECT count(1) counts";
        String limit = "limit " + (page - 1) * size + "," + size;

        List<HashMap<String, Object>> list = null;
        Long total = 0l;
        try {
            list = UserDaoSql.getInstance().queryBySql(listSql + sql + limit);
            total = UserDaoSql.getInstance().getCount(countSql + sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        if (null != list) {
            list = list.stream().map(bean -> voild(bean)).collect(Collectors.toList());
            return AjaxResult.successResult(list, total);
        }
        return AjaxResult.successResult(null, 0);
    }

    public static HashMap<String, Object> voild(HashMap<String, Object> bean) {
        Object url1 = bean.get("image1Url");
        if (url1 != null && ValidateUtil.isNotNull(url1.toString()) && ValidateUtil.isNotNetUrl(url1.toString())) {
            bean.put("image1Url", SYS_CONFIG_PATH.IMAGE_BASE_URL + url1.toString());
        }
        Object url2 = bean.get("image2Url");
        if (url2 != null && ValidateUtil.isNotNull(url2.toString()) && ValidateUtil.isNotNetUrl(url2.toString())) {
            bean.put("image2Url", SYS_CONFIG_PATH.IMAGE_BASE_URL + url2.toString());
        }
        Object url3 = bean.get("image3Url");
        if (url3 != null && ValidateUtil.isNotNull(url3.toString()) && ValidateUtil.isNotNetUrl(url3.toString())) {
            bean.put("image3Url", SYS_CONFIG_PATH.IMAGE_BASE_URL + url3.toString());
        }
        Object url4 = bean.get("image4Url");
        if (url4 != null && ValidateUtil.isNotNull(url4.toString()) && ValidateUtil.isNotNetUrl(url4.toString())) {
            bean.put("image4Url", SYS_CONFIG_PATH.IMAGE_BASE_URL + url4.toString());
        }
        return bean;
    }


    // --------------------------- 商家好店设置--------------------------------------------

    /**
     * @param token
     * @param shopId
     * @param topFine
     * @return
     * @desc 将指定的店铺设置成指定好店类型
     */
    @RequestMapping(value = "/admin/shop/top-fine")
    @ResponseBody
    public String top_fine_shop(String token, Long shopId,
                                @RequestParam(defaultValue = "0") Integer topFine) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (shopId == null) {
            return AjaxResult.errorResult("店铺id不能为空");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (shopInfo == null) {
            return AjaxResult.errorResult("未获取到商户信息");
        }
        if (topFine < 0) {
            return AjaxResult.errorResult("请选择设置的好店");
        }
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(PojoTables.ShopInfo)
                .append(" set topFineType = ").append(topFine)
                .append(",updateUser ='").append(user.getUsername()).append("'")
                .append(" where delFlag = 0 and id =").append(shopId);
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败,请稍后重试");
        }
        ShopMemory.getInstance().modifyById(shopId);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFO_UPDATE).setLong01(shopId);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }


    /**
     * @param token
     * @param agentId
     * @param topFine
     * @param page
     * @param size
     * @return
     * @desc 获取当前商圈指定类型的好店
     */
    @RequestMapping(value = "/admin/agent/top-fine/list", method = RequestMethod.POST)
    @ResponseBody
    public String top_fine_shop_list(String token, Long agentId, Integer topFine,
                                     String content,
                                     @RequestParam(defaultValue = "1") Integer page,
                                     @RequestParam(defaultValue = "20") Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (agentId == null) {
            return AjaxResult.errorResult("商圈id不能空");
        }
        if (topFine == null || topFine < 0) {
            return AjaxResult.errorResult("好店类型不能为空");
        }
        List<ShopInfo> shopInfoList = ShopMan.listOfAgentId(agentId, null, null, content, false, false, null, ShopCategoryMan.shopTypeShopping, false, false);
        if (ValidateUtil.isAbsList(shopInfoList)) {
            shopInfoList = shopInfoList.stream().filter(bean -> bean != null && (bean.getTopFineType() & topFine) > 0).collect(Collectors.toList());
            if (ValidateUtil.isAbsList(shopInfoList)) {
                JYPageUtils.PageList pageList = JYPageUtils.getList(shopInfoList, page, size);
                List<ShopInfoVO> resultList =
                        ((List<ShopInfo>) pageList.list).stream().map(bean -> {
                            ShopInfoVO shopInfoVO = new ShopInfoVO();
                            BeanUtils.copyProperties(bean, shopInfoVO);
                            if (ValidateUtil.isNotNull(shopInfoVO.getImageUrl()) && ValidateUtil.isNotNetUrl(shopInfoVO.getImageUrl())) {
                                String thumb = ImageService.getThumbnailImgUrl(shopInfoVO.getImageUrl(), bean.getImgUpVer(), bean.getThumbnailState());
                                shopInfoVO.setImageThumbnailUrl(thumb);
//                                shopInfoVO.setImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + shopInfoVO.getImageUrl());
                                shopInfoVO.setImageUrl(ImageService.getImgUrl(bean.getImgUpVer()) + shopInfoVO.getImageUrl());
                            }
                            return shopInfoVO;
                        }).collect(Collectors.toList());
                return AjaxResult.successResult(resultList, pageList.totalCount);
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    /**
     * @param token
     * @param agentId
     * @param topFine
     * @param page
     * @param size
     * @return
     * @desc 获取当前商圈指定类型的好店
     */
    @RequestMapping(value = "/admin/agent/no/top-fine-shop/list", method = RequestMethod.POST)
    @ResponseBody
    public String not_top_fine_shop_list(String token, Long agentId, Integer topFine,
                                         String content,
                                         @RequestParam(defaultValue = "1") Integer page,
                                         @RequestParam(defaultValue = "20") Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (agentId == null) {
            return AjaxResult.errorResult("商圈id不能空");
        }
        if (topFine == null || topFine < 0) {
            return AjaxResult.errorResult("好店类型不能为空");
        }
        List<ShopInfo> shopInfoList = ShopMan.listOfAgentId(agentId, null, null, content, false, false, null, ShopCategoryMan.shopTypeShopping, false, false);
        if (ValidateUtil.isAbsList(shopInfoList)) {
            shopInfoList = shopInfoList.stream().filter(bean -> bean != null && (bean.getTopFineType() & topFine) <= 0).collect(Collectors.toList());
            if (ValidateUtil.isAbsList(shopInfoList)) {
                JYPageUtils.PageList pageList = JYPageUtils.getList(shopInfoList, page, size);
                List<Map<String, Object>> resultList =
                        ((List<ShopInfo>) pageList.list).stream().map(bean -> {
                            Map<String, Object> map = new HashMap<>();
                            map.put("shopId", bean.getId());
                            map.put("username", bean.getOwnUsername());
                            map.put("shopName", bean.getShopName());
                            map.put("telephone", bean.getTelephone());
                            if (ValidateUtil.isNotNull(bean.getImageUrl()) && ValidateUtil.isNotNetUrl(bean.getImageUrl())) {
                                map.put("imageThumbnailUrl", ImageService.getThumbnailImgUrl(bean.getImageUrl(), bean.getImgUpVer(), bean.getThumbnailState()));
                                map.put("imageUrl", ImageService.getImgUrl(bean.getImgUpVer()) + bean.getImageUrl());
                            }
                            return map;
                        }).collect(Collectors.toList());
                return AjaxResult.successResult(resultList, pageList.totalCount);
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    // 批量设置店铺为指定好店类型
    @RequestMapping(value = "/admin/agent/top-fine-shop/batch/set", method = RequestMethod.POST)
    @ResponseBody
    public String top_fine_shop_batch_list(String token, Integer topFine, String shopIds) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (topFine == null) {
            return AjaxResult.errorResult("好店类型不能为空");
        }
        if (ValidateUtil.isNull(shopIds)) {
            return AjaxResult.errorResult("店铺列表不能为空");
        }
        Set<Long> shopIdSet = CommonUtils.splitToSet(shopIds, Long.class);
        StringBuilder sql = new StringBuilder();
        sql.append(" update ").append(PojoTables.ShopInfo)
                .append(" set updateUser ='").append(user.getUsername())
                .append("', ")
                .append(" topFineType = (topFineType|").append(topFine).append(")")
                .append(" where id in (").append(StringUtils.join(shopIdSet, ","))
                .append(") and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败,请稍后重试");
        }
        ShopMemory.getInstance().modify(StringUtils.join(shopIdSet, ","));
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.SHOP_INFOS_UPDATE).setStr01(StringUtils.join(shopIdSet, ","));
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return AjaxResult.successResult();
    }

    // 店铺申请为云店铺
    @RequestMapping("/shop/cloud-shop/apply")
    @ResponseBody
    public String cloudShopApply(String sysAppKey, String token) {
        SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
        if (customerInfo == null) {
            return AjaxResult.errorResult("为获取到客户端标识");
        }
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        ShopInfo info = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (info == null) {
            return AjaxResult.errorResult("未获取到商家信息");
        }
        try {
            ShopService.getInstance().shopApplyCloudShop(sysAppKey, info, user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        ShopInfo shop = ShopMemory.getInstance().getShopById(info.getId());
        if (shop != null) {
            ShopInfoVO vo = new ShopInfoVO();
            BeanUtils.copyProperties(shop, vo);
            ShopInfoExtra shopInfoExtra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shop.getId());
            if (shopInfoExtra != null) {
                vo.setCloudShopApplyState(shopInfoExtra.getCloudShopApplyState());
            }
            return AjaxResult.successResult(vo);
        }
        return AjaxResult.successResult();
    }


    // 商家上下班日志
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/work/logs")
    @ResponseBody
    public String adminShopWorkLog(String token, Long shopId, Long startTime, Long endTime, Integer page, Integer size) {
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.successResult(null, 0);
        }
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 20;
        }
        StringBuffer sql = new StringBuffer();
        sql.append("select * from ").append(PojoTables.SHOP_WORK_LOG)
                .append(" where shopId =").append(shopId);
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" and createTime > ").append(startTime);
        }
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" and createTime < ").append(endTime);
        }
        sql.append(" order by createTime desc");
        List<ShopWorkLog> list = new ArrayList<>();
        try {
            list = (List<ShopWorkLog>) DataDaoSql.getInstance().list(ShopWorkLog.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(null, 0);
        }
        JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
        if (pageList == null || !ValidateUtil.isAbsList(pageList.list)) {
            return AjaxResult.successResult(null, 0);
        }
        long totalCount = list.size();
        list = (List<ShopWorkLog>) pageList.list;
        List<ShopWorkLogVO> reList = new ArrayList<>();
        ShopWorkLogVO vo = null;
        for (ShopWorkLog log : list) {
            vo = new ShopWorkLogVO();
            BeanUtils.copyProperties(log, vo);
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(vo.getUsername());
            if (userInfo != null) {
                vo.setName(userInfo.getName());
            } else {
                vo.setName(vo.getUsername());
            }
            reList.add(vo);
        }
        return AjaxResult.successResult(reList, totalCount);
    }

    // 商家申请成为团购商家
    @RequestMapping("/shop/shop_category/apply")
    @ResponseBody
    public String cloudShopCategoryApply(String token, Integer shopCategory) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        ShopInfo info = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (info == null) {
            return AjaxResult.errorResult("未获取到商家信息");
        }
        if (shopCategory == null) {
            shopCategory = ShopCategoryMan.shopTypeGroup;
        }
        try {
            ShopService.getInstance().shopApplyShopCategory(info, shopCategory, user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        ShopInfo shop = ShopMemory.getInstance().getShopById(info.getId());
        if (shop != null) {
            ShopInfoVO vo = new ShopInfoVO();
            BeanUtils.copyProperties(shop, vo);
            ShopInfoExtra shopInfoExtra = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(shop.getId());
            if (shopInfoExtra != null) {
                vo.setShopCategoryApplyState(shopInfoExtra.getShopCategoryApplyState());
            }
            return AjaxResult.successResult(vo);
        }
        return AjaxResult.successResult();
    }

    // 添加积分商城(管理后台-城代管理-添加城代且开启积分功能才可以使用)
    @RequestMapping("/shop/intergral_shop/add")
    @ResponseBody
    public String addIntergralShop(String username) {
        if (!StringUtils.isNotBlank(username)) {
            return AjaxResult.errorResult("店主名称不能为空");
        }
        List<ShopInfo> shopInfoList = ShopMemory.getInstance().listOfIntegralShop(SHOP_IS_INTEGRAL.HAS_INTEGRAL_SHOP);
        if (ValidateUtil.isAbsList(shopInfoList)) {
            for (ShopInfo shopInfo : shopInfoList) {
                if (shopInfo.getOwnName().equals(username) && shopInfo.getCreateUser().equals(username)) {
                    // 已存在该代理的积分商城
                    return AjaxResult.errorResult("已存在该代理的积分商城");
                }
            }
        }
        long cTime = DateUtils.getCurrTime();
        // 创建一个默认的积分商城
        ShopInfo info = new ShopInfo();
        info.setDelFlag(0);
        info.setShopName("积分商城");
        info.setOwnName(username);
        info.setIsIntegralShop(1);
        info.setCreateTime(cTime);
        info.setCreateUser(username);
        info.setLat(0.00d);
        info.setLng(0.00d);
        try {
            UserDaoSql.getInstance().saveObj(PojoTables.ShopInfo, info);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("创建代理的积分商城失败,请稍后重试");
        }
        ShopMemory.getInstance().add(cTime);
        return AjaxResult.successResult();
    }
}
